Java 8 Streams : get non repeated counts

前端 未结 5 1817
南方客
南方客 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:30

    For completeness, here's a Java 8 way which doesn't make use of streams:

    Map frequencyMap = new LinkedHashMap<>(); // preserves order
    
    myList.forEach(element -> frequencyMap.merge(element, 1L, Long::sum)); // group, counting
    
    frequencyMap.values().removeIf(count -> count > 1); // remove repeated elements
    
    Set nonRepeated = frequencyMap.keySet(); // this is your result
    

    This uses Map.merge to fill the map with the count of each element. Then, Collection.removeIf is used on the values of the map, in order to remove the entries whose value is greater than 1.

    I find this way much more compact and readable than using streams.

提交回复
热议问题