Beenish Sajjad
Beenish Sajjad

Reputation: 43

GroupingBy in Java8-Streams

I am using Grouping-By in Streams:

1: I want to know how can i use "Grouping-By" twice in Collect method.

2: Secondly,What is the strategy to define return types in grouping?

1:

Map<String,String> sum1 = Items.items().stream()
                       .collect(Collectors.groupingBy(Items::getName,
                               Collectors.groupingBy(Items::getName)));

error message:

1:Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - incompatible types: inference variable D has incompatible equality constraints java.lang.String,java.lang.Integer at collectorsinjava.CollectorsInJava.main(CollectorsInJava.java:33)

2:

     Map<String, Map<String,Integer>> sum1 = Items.items().stream()
                .collect(Collectors.groupingBy(Items::getName,
                            Collectors.groupingBy(Items::getQuantity)));

error message:

2:Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - incompatible types: inference variable K has incompatible bounds equality constraints: java.lang.String lower bounds: java.lang.Integer at collectorsinjava.CollectorsInJava.main(CollectorsInJava.java:37)

This is my list of items:

List<Items> item = Arrays.asList(new Items("A",22,new BigDecimal("23.3")),
 new Items("B",33,new BigDecimal("19.99")),

 new Items("C",31,new BigDecimal("23.3")),

 new Items("D",22,new BigDecimal("19.99")),

 new Items("B",33,new BigDecimal("23.3")),

 new Items("C",31,new BigDecimal("19.99")),

 new Items("D",22,new BigDecimal("23.3"))
);

can someone please suggest how I can avoid the compilation errors?

Upvotes: 1

Views: 1779

Answers (1)

Ousmane D.
Ousmane D.

Reputation: 56413

You can group twice or however many times you want by chaining groupingBy collectors as you've done but the issue here is that the receiver type is incorrect.

the receiver type for the first query should be:

Map<String, List<Items>> resultSet = Items.items().stream()
            .collect(Collectors.groupingBy(Items::getName));

as there is no need to group by the same property twice.

when you have two or more grouping collectors chained together, you'll receive a multi-level map so therefore the receiver type for the second query should be:

Map<String, Map<Integer, List<Items>>> anotherResultSet

Otherwise, if you want to adapt a Collector to perform an additional finishing transformation then you're looking for a collectingAndThen.

Upvotes: 1

Related Questions