2

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"
1
  • It is not clear, Can you provide a constructive example?? Commented Sep 29, 2017 at 10:10

1 Answer 1

4

If I understood correctly:

map.entrySet()
   .stream()
   .flatmap(e -> e.getValue().stream().map(s -> Pair.of(e.getKey(), s)))
   .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

5 Comments

Great. Do you know how to do the reverse after that ? Actually I need to flatten in order to limit and after that group then like initially. I'm struggling with the groupBy but no success.
@CC. probably something along the lines of limit(10).collect(Collectors.groupingBy(Pair::getLeft, Collectors.toList()))
Yes, this is what I've tried but I keep having this error message for Pair::getLeft "non static method cannot be referenced from static context"
@CC. well without actual code, it hard to say exactly what does not work
@CC. don't get me wrong, but this is a different question right now... you could create a new one and get the desired answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.