In java 8 , Stream API help us to do our job with very clean and with less number of code. I am big fan of these stream API. But there are few operations which kind of help in solving the same type of problem and not sure when to use which operations Although it is not that much hard to choose between but just want to know any one have any specific use case for these. Operation which i am talking about is :-
Intermediate Operations :- min
and max
Terminal Operation: collect
with Collectors
class strategy using minBy
and maxBy
List<String> randomString= Arrays.asList("AA","AAA","A","AAAA","AAAAAA","AAAAAAAAAAAAAAAAAA");
String maxByIntermediateMax = randomString.stream().max(String :: compareTo).get();
String minByIntermediateMin = randomString.stream().min(String :: compareTo).get();
System.out.println("Intermediate Min() :- "+minByIntermediateMin+" Intermeidate Max() :- "+ maxByIntermediateMax);
String minByCollectorsMinBy = randomString.stream().collect(Collectors.minBy(Comparator.naturalOrder())).get();
String maxByCollectorsMaxBy = randomString.stream().collect(Collectors.maxBy(Comparator.naturalOrder())).get();
System.out.println("Collectors MinBy :- "+minByCollectorsMinBy+ " , Collectors maxBy is :- "+maxByCollectorsMaxBy);
Output
Intermediate Min() :- A Intermeidate Max() :- AAAAAAAAAAAAAAAAAA
Collectors MinBy :- A , Collectors maxBy is :- AAAAAAAAAAAAAAAAAA