Java 8 Streams:获得非重复计数 [英] Java 8 Streams : get non repeated counts
问题描述
这是输入和输出的SQL版本:
Here is the SQL version for the input and output :
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流实现它?
As 5 is non repeated.How do i implement it using JAVA 8 streams?
我在下面尝试过,但是显然给出了错误的结果
I tried below but obviously it is giving wrong result
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>
中,其中键是值本身,值是其重复的次数.稍后我们从结果映射中流式传输条目集,而filter
仅对计数为1
的条目进行流传输(这意味着它们不会重复),随后我们将map
传递至Entry::getKey
-从列出并计数.
Well you collect all the elements to a Map<Integer, Long>
, where the key is the value itself, and value is how many times it is repeated. Later we stream the entry set from that resulting map and filter
only those entries that that have a count of 1
(meaning they are not repeated), later we map
to Entry::getKey
- to get that value from the List and count.
这篇关于Java 8 Streams:获得非重复计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!