Home » Posts tagged 'Java8'
Tag Archives: Java8
Example of Java 8 Streams groupingBy feature
Statement: Let’s say you have a list of integers which you want to group into even and odd numbers.
Create a list of integers with four values 1,2,3 and 4:
List<Integer> numbers = new ArrayList<>(); numbers.add(1); numbers.add(2); numbers.add(3); numbers.add(4);
Now group the list into odd and even numbers:
Map<String, List<Integer>> numberGroups= numbers.stream().collect(Collectors.groupingBy(i -> i%2 != 0 ? "ODD" : "EVEN"));
This returns a map of (“ODD/EVEN” -> numbers).
Printing the segregated list along with its offset (ODD/EVEN):
for (String offset : numberGroups.keySet()) { for (Integer i : numberGroups.get(offset)) { System.out.println(offset +":"+i); } }
Outputs:
EVEN:2 EVEN:4 ODD:1 ODD:3
Refer Github for complete program.
Why Java 8 ?
In simple words java 8 allows us to write code more precisely and concisely, which is better than writing verbose code in the java versions prior to java 8.
Example: Let’s sort a collection of cars based on their speed.
Java versions prior to java 8 :
Collections.sort(fleet, new Comparator() { @Override public int compare (Car c1, Car c2) { return c1.getSpeed().compareTo(c2.getSpeed()); } }
Instead of writing a verbose code like above, using java 8 we can write the same code as:
Java 8 :
fleet.sort(Comparator.comparing(Car::getSpeed));
The above code is more concise and could be read as “sort fleet comparing Car’s speed”.
So why write a boilerplate code which is not related to the problem statement. Instead you can write concise code which is related to the problem statement and has SQL like readability.