I want to Group a list of objects by an attribute and then iterate the results using (Key, Value) pair.
I have found the way in Java 8 to group the list of objects with an attribute as follows
// filteredPageLog has the filtered results from PageLog entity.
Map<String, List<PageLog>> results =
filteredPageLog.stream().collect(Collectors.groupingBy(p -> p.getSessionId()));
But the results will have only entry sets(has values inside entrySet attribute). The keySet and valueSet will be having null values. I want to iterate something like
results.forEach((key,value) -> {
//logic
});
Use
results.entrySet().forEach(entry -> {
var key = entry.getKey();
var value = entry.getValue();
//logic
});
Dummy map:
Map<String,String> map = new HashMap() {{
put("1","20");
put("2","30");
}};
You can do it in two ways:
1. Map<K, V>.forEach() expects a BiConsumer<? super K,? super V> as
argument, and the signature of the BiConsumer<T, U> abstract
method is accept(T t, U u).
map.forEach((keys,values) -> { String k = keys ;
String v= values;
//logic goes here
});
2. Map<K, V>.entrySet().forEach() expects a Consumer<? super T> as
argument, and the signature of the Consumer<T> abstract
method is accept(T t).
map.entrySet().forEach((entry) -> { String k = entry.getKey();
String v= entry.getValue();
//logic goes here
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With