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.
)))
-
Enum is for the understainding purpose,the code is not copied,ghufranne– ghufranne2019年06月24日 11:57:17 +00:00Commented Jun 24, 2019 at 11:57
1 Answer 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>>
.
-
but I want only nested Map not list, could it not be possible? moreover thanks for your reponse.ghufranne– ghufranne2019年06月24日 11:29:05 +00:00Commented 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.daniu– daniu2019年06月24日 11:30:33 +00:00Commented 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.daniu– daniu2019年06月24日 11:32:46 +00:00Commented Jun 24, 2019 at 11:32
-
lr.get(0); is wrong, lr would be a map of list, the result of grouping by..ghufranne– ghufranne2019年06月24日 11:49:13 +00:00Commented Jun 24, 2019 at 11:49