【发布时间】:2018-05-28 09:01:20
【问题描述】:
我最近开始使用 collectAndThen,发现与我用于执行类似任务的其他编码程序相比,它花费的时间有点长。
这是我的代码:
System.out.println("CollectingAndThen");
Long t = System.currentTimeMillis();
String personWithMaxAge = persons.stream()
.collect(Collectors.collectingAndThen(
Collectors.maxBy(Comparator.comparing(Person::getAge)),
(Optional<Person> p) -> p.isPresent() ? p.get().getName() : "none"
));
System.out.println("personWithMaxAge - "+personWithMaxAge + " time taken = "+(System.currentTimeMillis() - t));
Long t2 = System.currentTimeMillis();
String personWithMaxAge2 = persons.stream().sorted(Comparator.comparing(Person::getAge).reversed())
.findFirst().get().name;
System.out.println("personWithMaxAge2 : "+personWithMaxAge2+ " time taken = "+(System.currentTimeMillis() - t2));
这里是输出:
CollectingAndThen
personWithMaxAge - Peter time taken = 17
personWithMaxAge2 : Peter time taken = 1
这表明collectingAndThen相对而言花费了更多时间。
所以我的问题是 - 我应该继续收集AndThen 还是有其他建议?
【问题讨论】:
-
这是你衡量事物的方式......
-
@Eugene 这并不是How to write a micro benchmark 的真正副本,尽管应用答案中的建议可能会有所帮助。
-
为什么不只是
persons.stream().max(Comparator.comparing(Person::getAge)).get().name? -
@AndyTurner 我只是想发布:D 此外,您可以将
get().name替换为map(p -> p.name).orElse('none')以避免 NoSuchElementExceptions。 -
这种差异几乎可以肯定取决于您如何设置测试。如果你颠倒顺序,然后你先做
personWithMaxAge2,会发生什么?
标签: java java-8 java-stream collectors collect