3

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
});

3 Answers3

3

Use

results.entrySet().forEach(entry -> {
     var key = entry.getKey();
     var value = entry.getValue();
//logic
});
talex
  • 16,886
  • 2
  • 27
  • 60
2

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
                                   });       
Naman
  • 21,685
  • 24
  • 196
  • 332
Vishwa Ratna
  • 5,007
  • 5
  • 28
  • 49
0

There are no tuples in Java. Here you can find more detailed explanation. You can iterate over keys, values or entries, but not tuples.

ilinykhma
  • 940
  • 1
  • 8
  • 14