Home > Blockchain >  Java Stream API, merge by key
Java Stream API, merge by key

Time:01-09

I have a stream of objects Couple<K, V> and I want to obtain a stream of Couple<K, List<V>>, where every element Couple<K, V> with the same value of K are merged in an object Couple<K, List<V>>.

This is the class Couple

public class Couple<K, V> {
    K k;
    V v;

    public Couple(K, V v) {
        this.k = k;
        this.v = v;
    }

    public K getK() {
        return this.k;
    }

    public V getV() {
        return this.v;
    }
}

I have to do this using Java stream

Thanks in advance

CodePudding user response:

You can try mapping the values and collect it as a list.

Couple<K, List<V>> mergeAsList() {
    return new Couple<>(getK(), Stream.of(this)
                                      .map(item -> item.getV())
                                      .collect(Collectors.toList()));
}

CodePudding user response:

Assuming your K properly override hashCode and equals methods to be used as a key in Map. However, you would be needing another class for desired output:

@AllArgsConstructor
class GroupedCouples {
  K k;
  List<V> v;
}

Assuming you have List<Couple> couples. You can do something like:

List<GroupedCouples> groupedCouples = couples.stream()
    .collect(Collectors.groupingBy(
        Couple::getK,
        Collectors.mapping(Couple::getV, Collectors.toList())
    )) // Map<K, List<V>> is built
    .entrySet()
    .stream() // Stream<Map.Entry<K, List<V>>>
    .map(e -> new GroupedCouples(e.getKey(), e.getValue()))
    .collect(Collectors.toList());

for more example refer

  •  Tags:  
  • Related