0

I have a list of objects as follows:

Rating {
Long id;
String aRating;
String bRating;
Date date;
//getters and Setters
}
List<Rating> list = //list with some values in it.

I have to convert the above list to a nested map:

Map<Date, Map<CustomEnum, String>> 
Enum CustomEnum {
 aRatingEnum("aRating", "someValue");
 bRatingEnum("bRating", "someValue");
 }

suppose List contains following values:

Id, Date, aRating, bRating
1 , 2/2/2019, A+, B+
2, 2/2/2018, A, B

then this needs to be converted to following map:

Map = {2/2/2019={aRatingEnum=A+, bRatingEnum=B+}, 2/2/2018 = {aRatingEnum=A, bRatingEnum=B}}

I have tried using java 8:

list.stream().collect(Collectors.groupingBy(x->x.getDate(), Collectors.toMap(
//here I am not able to proceed further how should I approach please help.
)))
asked Jun 24, 2019 at 10:52
1
  • Enum is for the understainding purpose,the code is not copied, Commented Jun 24, 2019 at 11:57

1 Answer 1

1

The toMap collects several items into a single collection. What you have is a single object (Rating) and want to create a Map out of it.

I think what you want is collectingAndThen which allows you to group by date and then do the transfer to the Map in the finishing Function.

list.stream()
 .collect(Collectors.collectingAndThen(
 Collectors.groupingBy(x->x.getDate(), 
 lr -> {
 Map<CustomEnum, String> result = new EnumMap<>();
 Rating r = lr.get(0); // take first rating for that date
 result.put(CustomEnum.aRatingEnum, r.getARating());
 result.put(CustomEnum.bRatingEnum, r.getBRating());
 return result;
 })));

Or refactor that lambda into a method, or use Map.of if you're using Java 9 or higher.

This will give you a Map<Date, Map<CustomEnum, String>>.

answered Jun 24, 2019 at 11:26
4
  • but I want only nested Map not list, could it not be possible? moreover thanks for your reponse. Commented Jun 24, 2019 at 11:29
  • @ghufranne The list is created because you might have more than one Rating per date. You'll have to decide how to handle several ratings. Commented Jun 24, 2019 at 11:30
  • @ghufranne not in the object, but you may have several objects for the same date in the list you're streaming. But I made a mistake anyway, I'll edit to let the finisher only use the first object. Commented Jun 24, 2019 at 11:32
  • lr.get(0); is wrong, lr would be a map of list, the result of grouping by.. Commented Jun 24, 2019 at 11:49

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.