Michał Wolnicki
Michał Wolnicki

Reputation: 285

java 8 stream group by two columns

So I have a class:

class AA {
private int number;
private String name; 
private String other; 

public AA(int number, String name, String other) {
    this.number = number;
    this.name = name;
    this.other = other;
}

public int getNumber() {
    return number;
}

public void setNumber(int number) {
    this.number = number;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getOther() {
    return other;
}

public void setOther(String other) {
    this.other = other;
}

@Override
public String toString() {
    return "AA{" + "number=" + number + ", name=" + name + ", other=" +  
other + '}';
}
}

And I creates a list:

    List<AA> list = new ArrayList<>();
    list.add(new AA(1, "1TEXT", "one"));
    list.add(new AA(2, "1TEXT", "two"));
    list.add(new AA(3, "2TEXT", "three"));
    list.add(new AA(1, "2TEXT", "four"));
    list.add(new AA(1, "2TEXT", "one"));

and I would like to group this through columns: number and other to fetch information like below:

 * number 1 : - one
              - four
 * number 2 : - two
 * number 3 : - three

Map<Integer,List<AA>> ss = list.stream().collect(Collectors.groupingBy(AA::getNumber));

above code will groub pnly through number.... Bu how to group by using two column ?

EDIT: I would like to get

Map<Integer, List<String>>

Upvotes: 1

Views: 3172

Answers (1)

Alexis C.
Alexis C.

Reputation: 93872

I don't think you're looking for a "second" group by. What you need is just to map the AA instances grouped by their other property. You can use the downstream collector mapping to achieve that.

Looking at the desired output, it seems you need to have a Set<String> as values instead of Lists.

import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toSet;

...

Map<Integer, Set<String>> map = 
    list.stream()
        .collect(groupingBy(AA::getNumber, mapping(AA::getOther, toSet())));

Upvotes: 4

Related Questions