Skip to main content

Posts

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}
Recent posts

Spring Data Rest Vs Spring Data JPA vs Hibernate

Spring Data JPA wrapped the implementation from the vendor(default Hibernate); Spring Data Rest will support features including convert the data service into HAL(hypertext Application language) based on rest service. Like Spring Data Elasticsearch and others, Spring Data JPA is one of the data service(for relational database) supported by Spring Data Rest

System.arraycopy() vs. Arrays.copyOf() in Java

source: https://www.programcreek.com/2015/03/system-arraycopy-vs-arrays-copyof-in-java/ System.arraycopy() vs. Arrays.copyOf() in Java   If we want to copy an array, we can use either  System.arraycopy()  or  Arrays.copyOf() . In this post, I use a simple example to demonstrate the difference between the two. 1. Simple Code Examples System.arraycopy() int [ ] arr = { 1 , 2 , 3 , 4 , 5 } ;   int [ ] copied = new int [ 10 ] ; System . arraycopy ( arr, 0 , copied, 1 , 5 ) ; //5 is the length to copy   System . out . println ( Arrays . toString ( copied ) ) ; Output: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 1, 2, 3, 4, 5, 0, 0, 0, 0] Arrays.copyOf() int [ ] copied = Arrays . copyOf ( arr, 10 ) ; //10 the the length of the new array System . out . println ( Arrays . toString ( copied ) ) ;   copied = Arrays . copyOf ( arr, 3 ) ; System . out . println ( Arrays . toString ( copied ) ) ; Output: [1, 2, 3, 4, 5, 0, 0, 0, 0, 0] [1, 2, 3] 2. The Major