グルーピングしながら、ソートした結果リストを求めることを
いざコーディングしようとすると、即時、思いつかないのが残念でメモ。
Collectors.collectingAndThen を使うのが重要
サンプル、以下、文字列の key と value があるクラスオブジェクト
public class Foo{ public String key; public String value; public Foo(String key, String value){ this.key = key; this.value = value; } }
あえて、value には、数値の文字列が入る約束として、この value で、グルーピング結果のコレクションがソート
されるようにする。
List の Map を生成
Map<String, List<Foo>> map = list.stream().collect(Collectors.groupingBy(e->e.key, Collectors.mapping(t->t, Collectors.collectingAndThen(Collectors.toCollection(ArrayList::new) , t->t.stream().sorted((o1, o2)->new Integer(o1.value).compareTo(new Integer(o2.value))) .collect(Collectors.toList()) ) )));
Set の Map を生成、 toList() を toSet() に返るだけですが。
Map<String, Set<Foo>> map = list.stream().collect(Collectors.groupingBy(e->e.key, Collectors.mapping(t->t, Collectors.collectingAndThen(Collectors.toCollection(ArrayList::new) , t->t.stream().sorted((o1, o2)->new Integer(o1.value).compareTo(new Integer(o2.value))) .collect(Collectors.toSet()) ) )));