CC.
CC.

Reputation: 2928

Java 8 reverse of grouping by

I'm trying to do a simple thing but I'm a bit stuck. I have the following :

Map<Date, Collection<String>>

So, for one Date I have a list of String (not a unique list). What I need is to transform this to the following format:

List<Object<Date,String>>

Each element of the first list could be present several times

(Ex of my main list: (date1, string1), (date1, string1), (date2, string2), (date2, string3)) 

I'm trying to do so with java stream but is not so obvious.

Any idea ?

Thanks.

EDIT: Here is what I have so far

    Map<Date, Collection<MyObject>> result = new HashMap<>();
    ......adding elements to the map...

                result.entrySet().stream().
                collect(Collectors.toMap(
                        e -> e.getKey(),
                        v -> v.getValue().stream().map( p ->  aggregateProductService.findProduct(customer.getPublicId(), p, setId)).
                                                   filter(Optional::isPresent).
                                                   map(Optional::get).
                                                   collect(toList())
                        )
                ).entrySet().stream().sorted(Map.Entry.comparingByKey()).flatMap(e -> e.getValue().stream().map(s -> Pair.of(e.getKey(), s))).
limit(10).
                           collect(toList()).stream().
                          collect(Collectors.groupingBy(Pair::getLeft, Collectors.toList()));

This piece of code does not compile. I have the following error:

Pair::getLeft "non static method cannot be referenced from static context"

Upvotes: 2

Views: 643

Answers (1)

Eugene
Eugene

Reputation: 121048

If I understood correctly:

map.entrySet()
   .stream()
   .flatmap(e -> e.getValue().stream().map(s -> Pair.of(e.getKey(), s)))
   .collect(Collectors.toList());

Upvotes: 4

Related Questions