Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

239
Views
Java 8 Streams - Grouping into Single value

I am currently working with a List<Map<String, Object>> where I am trying to group across various keys within the map. This seems to work nicely using the Java 8 Streams:

Map<Object, Map<Object, List<Map<String, Object>>>> collect =
   list
   .stream()
   .collect(Collectors.groupingBy(
       item -> item.get("key1"),
       Collectors.groupingBy(item -> item.get("key2"))
   ));

As expected this give me a Map<Object, Map<Object, List<Map<String, Object>>>> which works well where the possible grouped results are greater than 1.

I have various examples where the grouping being done will always result in a single item in the lowest level list, for example.

List of Rows

{
  [reference="PersonX", firstname="Person", dob="test", lastname="x"],
  [reference="JohnBartlett", firstname="John", dob="test", lastname="Bartlett"]
}

Grouped by reference

Currently - grouped into a list with 1 Map<String,Object>

[PersonX, { [reference="PersonX", firstname="Person", dob="test", lastname="x"]}],
[JohnBartlett, { [reference="JohnBartlett", firstname="John", dob="test", lastname="Bartlett"]}]

Preference - No List just a single Map<String,Object>

[PersonX, [reference="PersonX", firstname="Person", dob="test", lastname="x"]],
[JohnBartlett, [reference="JohnBartlett", firstname="John", dob="test", lastname="Bartlett"]]

is there a way within the streams to force the output for these instances to be Map<Object, Map<Object, Map<String, Object>>> - so a single Map<String,Object> rather than a List of them?

Any help would be greatly appreciated.

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

If I understood correctly, then for the cases where you are sure that there is a single item, you should just replace:

 .collect(Collectors.groupingBy(
   item -> item.get("key1"),
   Collectors.toMap(item -> item.get("key2"), Function.identity())
 ));

You can even provide a third argument as a BinaryOperator to merge your same entries (in case you need to)

about 4 years ago · Santiago Trujillo Report

0

Collectors.toMap() does exactly what you're looking to do.

Map<Object, Map<String, Object>> collect = maps.stream()
        .collect(Collectors.toMap(p -> p.get("reference"), Function.identity()));

Output:

{
  PersonX={firstname=Person, reference=PersonX, lastname=x, dob=test},
  JohnBartlett={firstname=John, reference=JohnBartlett, lastname=Bartlett, dob=test}
}

This will throw an IllegalStateException if you have a duplicate key, which is probably exactly what you want when you never expect there to be a duplicate record in your data:

Exception in thread "main" java.lang.IllegalStateException: Duplicate key JohnBartlett (attempted merging values {dob=test, lastname=Bartlett, reference=JohnBartlett, firstname=John} and {dob=test 2, lastname=Bartlett, reference=JohnBartlett, firstname=John})
    at java.base/java.util.stream.Collectors.duplicateKeyException(Collectors.java:133)
    at java.base/java.util.stream.Collectors.lambda$uniqKeysMapAccumulator$1(Collectors.java:180)
    at java.base/java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
    at java.base/java.util.AbstractList$RandomAccessSpliterator.forEachRemaining(AbstractList.java:720)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578)
    at so.UniqueKeyStreamExample.main(UniqueKeyStreamExample.java:22)
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!