How to check if exists any duplicate in Java 8 Streams?

前端 未结 5 2111
猫巷女王i
猫巷女王i 2020-12-01 07:26

In java 8, what\'s the best way to check if a List contains any duplicate?

My idea was something like:

list.size() != list.stream().distinct().count(         


        
5条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 07:45

    Started this class as a StreamTool, but I think there must be an even better way with reduce or similar:

    public class StreamTool {
    
        /**
         * Whether stream records are unique in that stream.
         * @param  Type of records
         * @param records
         * @return true if there are no duplicates, false otherwise
         */
        public static  boolean isUnique(Stream records) {
            return records.allMatch(new HashSet<>()::add);
        }
    }
    

提交回复
热议问题