Skip to main content

Posts

Showing posts from April, 2020

Java: Convert between int or Integer arrays to List with Java 8 features

#1 how to convert int[]/ Integer[] to list for int[]: int[] arr = {1, 2, 3}; //you have to box the primitive type of Integer List<Integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList()); for Integer: Integer[] arr = {1, 2, 3}; List<Integer> list = Array.asList(array); but cannot do: list.remove(0); // UnsupportedOperationException :( Here you cannot remove the 0 element because asList returns a fixed-size list backed by the specified array. So you should do something like: List<Object> newList = new ArrayList<>(Arrays.asList(array)); in order to make the newList modifiable. #2 how to convert Integer[] to list, and  to int[] Integer[] arr = {1, 2, 3}; //to list List<Integer> list = Array.asList(array); // to int[] int[] array = list.stream().mapToInt(x->x).toArray(); //to back to Integer[] Integer[] array = list.stream().mapToInt(x->x).boxed().toArray(Integer[]::new); more examples: Integer[] a = {1,3,5}