gpt4 book ai didi

Java 8 流 : get non repeated counts

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:57:52 24 4
gpt4 key购买 nike

这是输入和输出的 SQL 版本:

     with tab1 as (

select 1 as id from dual union all
select 1 as id from dual union all
select 2 as id from dual union all
select 2 as id from dual union all
select 5 as id from dual
)

select id from tab1 group by id having count(id)=1;

Output is Id=5 and count is 1

因为 5 是非重复的。我如何使用 JAVA 8 流实现它?

我在下面尝试过,但显然它给出了错误的结果

List<Integer> myList = new ArrayList<Integer>();
myList.add(1);
myList.add(1);
myList.add(2);
myList.add(2);
myList.add(5);

Long f = myList.stream()
.distinct().count();

System.out.println(f);

最佳答案

long result = myList.stream()
.collect(Collectors.groupingBy(
Function.identity(),
Collectors.counting()))
.entrySet()
.stream()
.filter(entry -> entry.getValue() == 1)
.map(Entry::getKey)
.count();

好吧,您将所有元素收集到 Map<Integer, Long> ,其中键是值本身,值是重复的次数。稍后我们从生成的 map 和 filter 流式传输条目集。只有那些计数为 1 的条目(意思是它们不重复),稍后我们 mapEntry::getKey - 从列表中获取该值并计数。

关于Java 8 流 : get non repeated counts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51879493/

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