Java 8 Stream - Find largest nested list

半腔热情 提交于 2019-12-22 08:55:15

问题


I have a Collection<List<SomeObject>> values

How can I find the collection with the largest list using Streams?

I have tried something like this, but it doesn't quite work

values.stream().max(e -> e.stream().max(List::size).get()).get()

But I get compilation error. Any ideas?


回答1:


I think you want

 values.stream().max(Comparator.comparingInt(List::size)).get()

If you need duplicates, the best solution I can think of would be something like

values.stream()
   .collect(Collector.of(
      ArrayList::new,
      (List<List<SomeObject>> best, List<SomeObject> elem) -> {
        if (best.isEmpty()) {
          best.add(elem);
        } else if (best.get(0).size() < elem.size()) {
          best.clear();
          best.add(elem);
        }
      },
      (best1, best2) -> {
        if (best1.isEmpty() || best2.isEmpty()
              || best1.get(0).size() == best2.get(0).size()) {
          best1.addAll(best2);
          return best1;
        } else if (best1.get(0).size() > best2.get(0).size()) {
          return best1;
        } else {
          return base2;
        }
      }));



回答2:


My StreamEx library provides a ready collector to find all the maximal elements:

List<List<SomeObject>> result = values.stream()
                .collect(MoreCollectors.maxAll(Comparator.comparingInt(List::size)));


来源:https://stackoverflow.com/questions/34776248/java-8-stream-find-largest-nested-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!