您的代码将需要遍历所有元素。如果要确保没有重复的简单方法,例如
public static <T> boolean areAllUnique(List<T> list){ Set<T> set = new HashSet<>(); for (T t: list){ if (!set.add(t)) return false; } return true;}会更有效,因为它可以
false在找到第一个非唯一元素时立即为您提供。
此方法也可以重写为(假设非并行流和线程安全的环境),使用
Stream#allMatch该方法也很短路(对于不满足所提供条件的第一个元素,立即返回false)
public static <T> boolean areAllUnique(List<T> list){ Set<T> set = new HashSet<>(); return list.stream().allMatch(t -> set.add(t));}public static <T> boolean areAllUnique(List<T> list){ return list.stream().allMatch(new HashSet<>()::add);}


