Reputation: 553
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
});
Upvotes: 3
Views: 856
Reputation: 6420
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
});
Upvotes: 2
Reputation: 990
There are no tuples in Java. Here you can find more detailed explanation. You can iterate over keys, values or entries, but not tuples.
Upvotes: 0
Reputation: 20542
Use
results.entrySet().forEach(entry -> {
var key = entry.getKey();
var value = entry.getValue();
//logic
});
Upvotes: 3