gpt4 book ai didi

Java流API : How to use method reference?

转载 作者:行者123 更新时间:2023-12-01 17:44:01 24 4
gpt4 key购买 nike

有代码

     class Person {
private ZonedDateTime date ;
private int regionId;
private int centerId;
private int amount1;
private float percent1;
}

List<Person> entityList = new ArrayList<>();

我按年月分组,如下所示:

  listPerson.stream()
.collect(Collectors.groupingBy(i -> i.getDate().getMonth(),Collectors.collectingAndThen(Collectors.toList(),
l -> {
Integer sumAmount1 = l.stream().collect(Collectors.summingInt(i -> i.getAmount1()));
Double avgPerc1 = l.stream().collect(Collectors.averagingDouble(i -> i.getPercent1()));
List<String> data = new ArrayList<>();
data.add(Integer.toString(sumAmount1));
data.add(Double.toString(avgPerc1));
return data;
}
))).forEach((k,v) -> System.out.println(k.getValue() + "-" + v.toString()));

我还以相同的方式按年份、regionId、centerId 进行分组:

 listPerson.stream()
.collect(Collectors.groupingBy(i -> i.getDate().getYear(),Collectors ......

但是我有很多重复的代码,其中部分与

l -> {...} 

重复了很多次。如何使用方法引用代替 l -> {...}?

最佳答案

IntelliJ 确实可以为您做到这一点。您甚至不必考虑它。

enter image description here

提示的键盘快捷键(黄色)是AltEnter

这就是我最终得到的结果

public static void main(String[] args)
{
List<Person> listPerson = null;

listPerson.stream()
.collect(Collectors.groupingBy(i -> i.getDate().getMonth(), Collectors.collectingAndThen(Collectors.toList(),
Scratch::apply
)))
.forEach((k,v) -> System.out.println(k.getValue() + "-" + v.toString()));
}

private static List<String> apply(List<Person> l)
{
int sumAmount1 = l.stream().mapToInt(Person::getAmount1).sum();
Double avgPerc1 = l.stream().collect(Collectors.averagingDouble(Person::getPercent1));
List<String> data = new ArrayList<>();
data.add(Integer.toString(sumAmount1));
data.add(Double.toString(avgPerc1));
return data;
}

关于Java流API : How to use method reference?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57724241/

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