1.java8獲取list集合中重復(fù)的元素
//單獨(dú)String集合
List<String> list = Arrays.asList("a","b","a","c","d","b");
List<String> collect = list.stream().filter(i -> i != "") // list 對應(yīng)的 Stream 并過濾""
.collect(Collectors.toMap(e -> e, e -> 1, Integer::sum)) // 獲得元素出現(xiàn)頻率的 Map,鍵為元素,值為元素出現(xiàn)的次數(shù)
.entrySet()
.stream() // 所有 entry 對應(yīng)的 Stream
.filter(e -> e.getValue() > 1) // 過濾出元素出現(xiàn)次數(shù)大于 1 (重復(fù)元素)的 entry
.map(Map.Entry::getKey) // 獲得 entry 的鍵(重復(fù)元素)對應(yīng)的 Stream
.collect(Collectors.toList());
System.out.println(collect);
2.java8根據(jù)List對象屬性獲取重復(fù)數(shù)據(jù)和獲取去重后數(shù)據(jù)
2.1獲取重復(fù)數(shù)據(jù)
List<Person> personList = new ArrayList<Person>();
personList.add(new Person("張三", 8, 3000));
personList.add(new Person("李四", 18, 5000));
personList.add(new Person("王五", 28, 7000));
personList.add(new Person("孫六", 38, 9000));
personList.add(new Person("孫六", 38, 9000));
personList.add(new Person("孫六", 38, 10000));
//1.先根據(jù)得到一個(gè)屬于集合 姓名
List<String> uniqueList = personList.stream().collect(Collectors.groupingBy(Person::getName, Collectors.counting()))
.entrySet().stream().filter(e -> e.getValue() > 1)
.map(Map.Entry::getKey).collect(Collectors.toList());
uniqueList.forEach(p -> System.out.println(p));
//計(jì)算兩個(gè)list中的重復(fù)值 3條數(shù)據(jù)
List<Person> reduce1 = personList.stream().filter(item -> uniqueList.contains(item.getName())).collect(Collectors.toList());
System.out.println(reduce1.toString());
//2.根據(jù)多個(gè)屬性獲取重復(fù)數(shù)據(jù),只能重復(fù)操作得到重復(fù)的數(shù)據(jù) 工資
List<Integer> collect1 = reduce1.stream().collect(Collectors.groupingBy(Person::getWages, Collectors.counting()))
.entrySet().stream().filter(e -> e.getValue() > 1)
.map(Map.Entry::getKey).collect(Collectors.toList());
//計(jì)算兩個(gè)list中的差集
List<Person> collect2 = reduce1.stream().filter(item -> collect1.contains(item.getWages())).collect(Collectors.toList());
System.out.println(collect2.toString());
結(jié)果: 根據(jù)多個(gè)屬性獲取重復(fù)數(shù)據(jù),還在摸索中,歡迎大家來指點(diǎn)?。。。?!
文章來源:http://www.zghlxwxcb.cn/news/detail-528891.html
2.2獲取去重后數(shù)據(jù)
List<Person> personList = new ArrayList<Person>();
personList.add(new Person("張三", 8, 3000));
personList.add(new Person("李四", 18, 5000));
personList.add(new Person("王五", 28, 7000));
personList.add(new Person("孫六", 38, 9000));
personList.add(new Person("孫六", 38, 9000));
personList.add(new Person("孫六", 38, 10000));
//去重
List<Person> unique = personList.stream().collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new));
System.out.println("unique:"+unique.toString());
結(jié)果:文章來源地址http://www.zghlxwxcb.cn/news/detail-528891.html
到了這里,關(guān)于JAVA8 獲取list集合中重復(fù)的元素和獲取去重?cái)?shù)據(jù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!