gpt4 book ai didi

带列表的 Java 流

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

我对流及其工作方式不熟悉,我正在尝试获取列表中添加的特定对象的出现次数。

我找到了一种使用Collections来做到这一点的方法。其过程如下:

for (int i = 0; i < countries.size(); i++) {
int occurrences = Collections.frequency(countries, countries.get(i));
}

但我想使用流。我对流使用的方法是:

countries.parallelStream().filter(p -> p.contentEquals(countries.get(countries.size()-1))).count()

这只返回当前对象及其出现次数,而不是我想要所有对象及其出现次数。

编辑:

`private final ArrayList<String> countries = new ArrayList<>();

dataset.setValue(countries.parallelStream()
.filter(p -> p.contentEquals(countries.get(countries.size()-1)) )
.count(),
"",
countries.get(countries.size()-1)); //sets the graph for the given country
@Override
public void addCountries(String country) {
countries.add(country);
}

@Override
public void removeCountries(int country) {
countries.remove(country);
}`

我正在制作一个图表。 dataset.setValue()的第一个语句是该国家/地区出现的次数。必须对每个国家/地区执行此操作,以便您可以查看某个国家/地区出现了多少次。希望这有帮助

the graph

编辑2:已解决!

countries.stream().distinct().forEach(o -> 
dataset.setValue(Collections.frequency(countries, o),
"",
o)); //sets the graph for the given country

最佳答案

您还可以使用分组收集器:

Collection<Integer> collection = Arrays.asList(1, 2, 1, 4, 2);
final Map<Integer, Long> map = collection.stream().collect(
Collectors.groupingBy(el -> el, Collectors.counting()));
System.out.println(map);

这会产生

{1=2, 2=2, 4=1}

关于带列表的 Java 流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47759319/

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