Java 8 Streams : get non repeated counts

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

    Another option for you to consider:

        //Create a map where the key is the element you want to count and the value is the actual count
        Map countByItem = myList.stream()
            .collect(Collectors.groupingBy(
                    Function.identity(), //the function that will return the key
                    Collectors.counting())); //the function that will actually count the occurences
    
        //Once you have that map, all you need to do is filter for the registers with count == 1
        List result = countByItem.entrySet().stream()
            .filter(entry -> entry.getValue() == 1)
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());
    

提交回复
热议问题