LoginSignup
0
0

More than 1 year has passed since last update.

Java List を Group, Sort など

Last updated at Posted at 2019-02-05

List をグループごとに分けてソート処理

// グループ
Map<String, List<Object>> map = list.stream().collect(//
    Collectors.groupingBy(o -> o.getKey1()));
// 複数キー
Map<String, List<Object>> map = list.stream().collect(//
    Collectors.groupingBy(o -> o.getKey1() + o.getKey2()));
// 複数キー の null ざつに対応
Map<String, List<Object>> map = list.stream().collect(//
    Collectors.groupingBy(t -> t.getKey1() + (t.getKey2() == null ? "" : t.getKey2())));
 
// ソート
Comparator<Object> comparator = //
    Comparator.comparing(Object::getSort1, Comparator.nullsFirst(Comparator.naturalOrder()))//
    .thenComparing(Object::getSort2, Comparator.nullsFirst(Comparator.naturalOrder()))//
    .thenComparing(Object::getSort3, Comparator.nullsFirst(Comparator.naturalOrder()));
// limit
map.entrySet().forEach(e -> e.getValue().stream().sorted(comparator).limit(100).forEach(l -> System.out.println(e.getKey() + ":" + l.getValue())));

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0