gpt4 book ai didi

Java 8 Stream API min() 和 max() 与收集器 minBy() 和 maxBy()

转载 作者:行者123 更新时间:2023-12-05 04:48:34 25 4
gpt4 key购买 nike

<分区>

在 java 8 中,Stream API 帮助我们以非常干净和更少的代码来完成我们的工作。我是这些流 API 的忠实粉丝。但是很少有哪种操作有助于解决同一类型的问题,并且不确定何时使用哪种操作虽然在两者之间做出选择并不难,但只是想知道任何人对这些有任何特定的用例。我所说的操作是:-

中间操作:- minmax

终端操作:collectCollectors 类策略使用 minBymaxBy

List<String> randomString= Arrays.asList("AA","AAA","A","AAAA","AAAAAA","AAAAAAAAAAAAAAAAAA");
String maxByIntermediateMax = randomString.stream().max(String :: compareTo).get();
String minByIntermediateMin = randomString.stream().min(String :: compareTo).get();
System.out.println("Intermediate Min() :- "+minByIntermediateMin+" Intermeidate Max() :- "+ maxByIntermediateMax);
String minByCollectorsMinBy = randomString.stream().collect(Collectors.minBy(Comparator.naturalOrder())).get();
String maxByCollectorsMaxBy = randomString.stream().collect(Collectors.maxBy(Comparator.naturalOrder())).get();
System.out.println("Collectors MinBy :- "+minByCollectorsMinBy+ " , Collectors maxBy is :- "+maxByCollectorsMaxBy);

输出

Intermediate Min() :- A Intermeidate Max() :- AAAAAAAAAAAAAAAAAA
Collectors MinBy :- A , Collectors maxBy is :- AAAAAAAAAAAAAAAAAA

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com