5

I have two object. The first one:

public final class Object1 {
    private String a;
    private String b;
    // constructor getter and setter
}

The second one:

public class Object2 {
    private BigDecimal value1;
    private BigDecimal value2;
    // constructor getter and setter
}

I have a Map<Object1, Object2>:

    Object1{a="15", b="XXX"}, Object2{value1=12.1, value2=32.3}
    Object1{a="15", b="YYY"}, Object2{value1=21.1, value2=24.3}
    Object1{a="16", b="AAA"}, Object2{value1=34.1, value2=45.3}
    Object1{a="15", b="BBB"}, Object2{value1=23.1, value2=65.3}
    Object1{a="15", b="DDD"}, Object2{value1=23.1, value2=67.3}
    Object1{a="17", b="CCC"}, Object2{value1=78.1, value2=2.3}
........

I want to group this map with the same a in a list of Object2 like:

a="15", {{value1=12.1, value2=32.3}, {value1=21.1, value2=24.3}, {value1=23.1, value2=65.3}, {value1=23.1, value2=67.3}},
a="16", {{value1=34.1, value2=45.3}}
...

I try something like this:

Map<String, List<Object2>> map1 = map.entrySet()
   .stream()             
   .collect(Collectors.toMap(e -> e.getKey().getA(), list of object with this key);
1

1 Answer 1

5
yourMap.entrySet()
       .stream()
       .collect(Collectors.groupingBy(e -> e.getKey().getA(),
               Collectors.mapping(Entry::getValue, Collectors.toList())))
Sign up to request clarification or add additional context in comments.

6 Comments

How can i group this map with the same 'a' and the mean value of all value1 in the list of object2 in a collect statement? Something like a="15", mean value of Object2.value1, a="16", mean value of Object2.value1
@emoleumassi so basically u want a Map<String, BigDecimal> where value is the min from all those value1?
yes. a Map<String, BigDecimal> where value is the min from all those value1
@emoleumassi map.entrySet() .stream() .collect(Collectors.groupingBy(x -> x.getKey().getA(), Collectors.mapping(x -> x.getValue().getValue1(), Collectors.collectingAndThen( Collectors.minBy( Comparator.naturalOrder()), Optional::get))))
@Eugene or just map.entrySet().stream().collect(Collectors.toMap(x -> x.getKey().getA(), x -> x.getValue().getValue1(), BigDecimal::min)), which is quite shorter
|

Your Answer

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.