Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

240
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda