Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group a list of objects by an attribute and then iterate the results using (Key, Value) pair?

Tags:

java

java-8

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
});
like image 369
Mohammed Shirhaan Avatar asked Dec 29 '25 09:12

Mohammed Shirhaan


2 Answers

Use

results.entrySet().forEach(entry -> {
     var key = entry.getKey();
     var value = entry.getValue();
//logic
});
like image 63
talex Avatar answered Dec 31 '25 21:12

talex


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
                                   });       
like image 26
Vishwa Ratna Avatar answered Dec 31 '25 22:12

Vishwa Ratna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!