Example of Collectors minBy in Lambda expression
UPDATED: 04 June 2015
Tags:
Collectors
,
List
,
Stream
Collectors.minBy
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 CollectorsMinBy { public static void main(String[] args) { /* Create and add elements in List of String */ List<String> listStrings = new ArrayList<String>(); listStrings.add("Vicky"); listStrings.add("Carl"); listStrings.add("Leonard"); /* Java 8: Use stream over List of String and use `minBy` with Comparator */ Optional<String> optionalString = listStrings.stream() .collect(Collectors.minBy(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("Minimum String: " + resultString); /* Create and add elements in List of Integer */ List<Integer> listIntegers = new ArrayList<Integer>(); listIntegers.add(10); listIntegers.add(5); listIntegers.add(101); /* Java 8: Use stream over List of Integer and use `minBy` with Comparator */ Optional<Integer> optionalInteger = listIntegers.stream() .collect(Collectors.minBy(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("Minimum 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
Minimum String: Carl Minimum Integer: 5
Tags:
Collectors
,
List
,
Stream
0 comments :