Java 8 Streams : get non repeated counts

前端 未结 5 1718
南方客
南方客 2021-01-18 11:54

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         


        
5条回答
  •  悲哀的现实
    2021-01-18 12:22

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

    Well you collect all the elements to a Map, 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.

提交回复
热议问题