Example of Collectors maxBy in Lambda expression
UPDATED: 03 June 2015
Tags:
Collectors
,
List
,
Stream
Collectors.maxBy
This static method from package java.util.stream and class Collectors used to find maximum value from given Collection. This method takes Comparator as an argument.
Source Code
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class CollectorsMaxBy {
public static void main(String[] args) {
/* Create and add elements in List of String */
List listStrings = new ArrayList<String>();
listStrings.add("Vicky");
listStrings.add("Carl");
listStrings.add("Leonard");
/* Java 8: Use stream over List of String and use `maxBy` with Comparator */
Optional optionalString = listStrings.stream()
.collect(Collectors.maxBy(new Comparator<String>() {
public int compare(String str1, String str2) {
return str1.compareTo(str2);
}
}));
/* Check value is available in `Optional` */
String resultString = optionalString.isPresent() ? optionalString.get() : "No String found";
/* Print the resultString */
System.out.println("Maximum String: " + resultString);
/* Create and add elements in List of Integer */
List listIntegers = new ArrayList<Integer>();
listIntegers.add(10);
listIntegers.add(5);
listIntegers.add(101);
/* Java 8: Use stream over List of Integer and use `maxBy` with Comparator */
Optional optionalInteger = listIntegers.stream()
.collect(Collectors.maxBy(new Comparator<Integer>() {
public int compare(Integer integer1, Integer integer2) {
return integer1 - integer2;
}
}));
/* Check value is available in `Optional` */
Integer resultInteger = optionalInteger.isPresent() ? optionalInteger.get() : 0;
/* Print the resultInteger */
System.out.println("Maximum Integer: " + resultInteger);
}
}
Note: Don't call .get() directly on .collect(Collectors.minBy(new Comparator()) because if there is no element in List then it'll throw an exception java.util.NoSuchElementException: No value present. Always get value in Optional and check isPresent().
Output
Maximum String: Vicky Maximum Integer: 101
Tags:
Collectors
,
List
,
Stream

0 comments :