-邵阳网络公司-邵阳网站建设|邵阳网站制作,大联盟平台推广,aspnet网站开发,自己做一款app需要多少钱利用HashSet
创建了一个HashSet用于存储唯一的字段值#xff0c;并创建了一个新的列表uniqueList用于存储去重后的对象。遍历原始列表时#xff0c;如果字段值未在HashSet中出现过#xff0c;则将其添加到HashSet和uniqueList中。 ListPerson originalList new Ar…利用HashSet
创建了一个HashSet用于存储唯一的字段值并创建了一个新的列表uniqueList用于存储去重后的对象。遍历原始列表时如果字段值未在HashSet中出现过则将其添加到HashSet和uniqueList中。 ListPerson 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));HashSetString uniqueSet new HashSet();ListPerson uniqueList new ArrayList();for (Person person : originalList) {if (uniqueSet.add(person.getName())) {uniqueList.add(person);}}System.out.println(uniqueList);利用Stream ListPerson 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));ListPerson uniqueList originalList.stream().collect(Collectors.toMap(Person::getName, person - person, (p1, p2) - p1)).values().stream().collect(Collectors.toList());System.out.println(uniqueList);ListPerson 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));ListPerson list new ArrayList(originalList);list list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() - new TreeSet(Comparator.comparing(Person::getName))), ArrayList::new));System.out.println(uniqueList);