I have a List of Map that i want to group it by the key nom using java streams.
[
{
"dateDebut": "2018-07-01T00:00:00.000+0000",
"nom": "Julien Mannone",
"etat": "Impayé"
},
{
"dateDebut": "2018-08-01T00:00:00.000+0000",
"nom": "Julien Mannone",
"etat": "Impayé"
},
{
"dateDebut": "2018-10-01T00:00:00.000+0000",
"nom": "Mathiew Matic",
"etat": "payé"
},
{
"dateDebut": "2018-10-01T00:00:00.000+0000",
"nom": "Ash Moon",
"etat": "payé"
}
]
so i want as a result something like this
{
"Julien Mannone":[
{
"dateDebut":"2018-07-01T00:00:00.000+0000",
"etat":"Impayé"
},
{
"dateDebut":"2018-08-01T00:00:00.000+0000",
"etat":"Impayé"
}
],
"Mathiew Matic":[
{
"dateDebut":"2018-10-01T00:00:00.000+0000",
"etat":"payé"
}
],
"Ash Moon":[
{
"dateDebut":"2018-10-01T00:00:00.000+0000",
"etat":"payé"
}
]
}
As a beginner in using streams I have made some research I found some codes like that
Map<String, List<Map>> afterFormatting =
beforeFormatting.stream()
.flatMap(m -> m.entrySet().stream())
.collect(groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, toList())));
but that doesn't do the job for me
mapper is a stateless function which is applied to each element and the function returns the new stream. Example 1 : Stream map() function with operation of number * 3 on each element of stream. // given function to this stream.
Java 8 Stream's map method is intermediate operation and consumes single element forom input Stream and produces single element to output Stream. It simply used to convert Stream of one type to another. Let's see method signature of Stream's map method.
Seems like you're simply looking for:
Map<String, List<Map<String, String>>> afterFormatting =
beforeFormatting.stream()
.collect(Collectors.groupingBy(map -> map.get("nom")));
or if you don't want each Map<String, String>
in the result set to contain the "nom" entry then you can do as follows:
Map<String, List<Map<String, String>>> afterFormatting =
beforeFormatting.stream()
.collect(Collectors.groupingBy(map -> map.get("nom"),
Collectors.mapping(map -> {
Map<String, String> temp = new HashMap<>(map);
temp.remove("nom");
return temp;
}, Collectors.toList())));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With