Cheatsheet - Java

Updated: 2018-12-25

Join As String

List<BigDecimal> buffer = ...
String s = buffer.stream()
              .map(x -> x.toString())
              .collect(Collectors.joining(",")));

Array to Stream

Arrays.stream(array);

String to IntStream

IntStream is = "abc".chars();

Array to Immutable List

private static final Thing[] PRIVATE_VALUES = { ... };
public static final List<Thing> VALUES =
    Collections.unmodifiableList(Arrays.asList(PRIVATE_VALUES));

Arrays.asList does not return ArrayList, so does not support addAll() or add(), will throw UnsupportedOperationException

Convert to string array

String[] y = x.toArray(new String[0]);

Primitive Array To List

Use boxed()

int[] nums = new int[]{1,2,3};
List<Integer> list = Arrays.stream(nums).boxed().collect(Collectors.toList());

Array To List

Integer[] nums = new Integer[]{1,2,3};
List<Integer> list = Arrays.stream(nums).collect(Collectors.toList());

Create ArrayList From Array

ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(1, 2, 3, 4));

Init

Init Stream

Stream<Integer> intStream = Stream.of(1,2,3,4);

Init List

List<Integer> = Arrays.asList(4,9,16,25,36);

Init EnumSet

EnumSet.of(Style.BOLD, Style.ITALIC);

Init Array

String[] s = {"asf", "asdf"};