利用HashSet
创建了一个HashSet用于存储唯一的字段值,并创建了一个新的列表uniqueList用于存储去重后的对象。遍历原始列表时,如果字段值未在HashSet中出现过,则将其添加到HashSet和uniqueList中。
List<Person> originalList = new ArrayList<>();originalList.add(new Person(1, "Alice"));originalList.add(new Person(2, "Bob"));originalList.add(new Person(3, "Alice"));originalList.add(new Person(4, "Charlie"));originalList.add(new Person(5, "Alice"));HashSet<String> uniqueSet = new HashSet<>();List<Person> uniqueList = new ArrayList<>();for (Person person : originalList) {if (uniqueSet.add(person.getName())) {uniqueList.add(person);}}System.out.println(uniqueList);
利用Stream
List<Person> originalList = new ArrayList<>();originalList.add(new Person(1, "Alice"));originalList.add(new Person(2, "Bob"));originalList.add(new Person(3, "Alice"));originalList.add(new Person(4, "Charlie"));originalList.add(new Person(5, "Alice"));List<Person> uniqueList = originalList.stream().collect(Collectors.toMap(Person::getName, person -> person, (p1, p2) -> p1)).values().stream().collect(Collectors.toList());System.out.println(uniqueList);
List<Person> originalList = new ArrayList<>();originalList.add(new Person(1, "Alice"));originalList.add(new Person(2, "Bob"));originalList.add(new Person(3, "Alice"));originalList.add(new Person(4, "Charlie"));originalList.add(new Person(5, "Alice"));List<Person> list = new ArrayList<>(originalList);list = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new));System.out.println(uniqueList);