Java8 Imp stream Snippets:
(_grouping By):
1) HashMap to Linked HashMap:
params.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue,
(e1,e2)->e2,LinkedHashMap::new));
2)Sum of HashMap Values:
params.values().stream().mapToInt(Integer::valueOf).sum();
3)Grouping By:
Map<Integer,List<String>> params=
users.stream().collect(Collectors.groupingBy(User::getId,
Collectors.mapping(User::getName,Collectors.toList())));
Map<Integer, EmployeeToMap> params=employees.stream()
.collect(Collectors.toMap(e-> e.getId(),
Function.identity(),(o1, o2) -> o1, LinkedHashMap::new));
4)Summing Int:
Map<Integer,Integer> params=
users.stream().collect(Collectors.groupingBy(User::getId,
Collectors.summingInt(e->1)));
Map<String,Integer> params = Stream.of(str.split(""))
.collect(Collectors.toList()).stream()
.collect(Collectors.groupingBy(String::valueOf,
LinkedHashMap::new,Collectors.summingInt(e->1)));
(_flatmap):
User -> List<Address> = the Scenario we need to get only User details
List<User> users1 = users.stream()
.filter(employee -> employee.getAddresses().stream()
.anyMatch(adr -> adr.getId().startsWith("1")))
.collect(Collectors.toList());
List<Address> addresses1 =
users.stream().map(User::getAddresses).flatMap(Collection::stream)
.filter(ad -> ad.getId().equals("1")).collect(Collectors.toList());
Finding Max & Min Value:
-> values.stream().max(Comparator.comparing(Integer::valueOf)).get()
-> values.stream().min(Comparator.comparing(Integer::valueOf)).get()
Sum of Values:
-> values.stream().mapToInt(Integer::intValue).sum()
Average Value:
values.stream().mapToInt(Integer::intValue).average().getAsDouble()
Comments
Post a Comment