Java 8 Streams : get non repeated counts

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

    You may do it like so,

    Map countByNumber = myList.stream()
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    List uniqueNumbers = myList.stream()
        .filter(n -> countByNumber.get(n) == 1)
        .collect(Collectors.toList());
    

    First create a map using the value and the number of occurences. Then iterate over the List of numbers, get the occurences from the map for each number. If the number of occurences is 1, then collect it into a separate container.

    If you want to do it in one go, here it is.

    List uniqueNumbers = myList.stream()
        .collect(Collectors.collectingAndThen(Collectors.groupingBy(Function.identity(), 
            Collectors.counting()),
        m -> myList.stream().filter(n -> m.get(n) == 1).collect(Collectors.toList())));
    

提交回复
热议问题