获取list集合中重复的元素
作者:互联网
方法1
List<String> words = Arrays.asList("a", "b", "c", "d", "a", "d"); List<String> results = HashMultiset.create(words).entrySet().stream() .filter(w -> w.getCount() > 1) .map(Multiset.Entry::getElement) .collect(Collectors.toList()); System.out.println(results);
方法2
可以修改返回值 返回去重的集合
public static <E> List<E> getListDuplicateElements(List<E> list){ List<E> words = list; Set<E> repeated = new HashSet<>(); List<E> results = new ArrayList<>(); for (E word : words) { if (!repeated.add(word)) { results.add(word); } } return results; }
方法3
导入guava依赖
<!-- https://mvnrepository.com/artifact/com.google.guava/guava --> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>31.0-jre</version> </dependency>
List<String> words = Arrays.asList("a", "b", "c", "d", "a", "d"); List<String> results = new ArrayList<>(); for (Multiset.Entry<String> entry : HashMultiset.create(words).entrySet()) { if (entry.getCount() > 1) { results.add(entry.getElement()); } } System.out.println(results);
Lambda 来使用guava
List<String> words = Arrays.asList("a", "b", "c", "d", "a", "d"); List<String> results = HashMultiset.create(words).entrySet().stream() .filter(w -> w.getCount() > 1) .map(Multiset.Entry::getElement) .collect(Collectors.toList()); System.out.println(results);
方法4
public List getRepeatList(List list) { List list2 = new ArrayList(); for (int i = 0; i < list.size(); i++) { for (int j = i + 1; j < list.size(); j++) { if (list.get(i) !="" && list.get(i).equals(list.get(j))) { list2.add(list.get(i)); break; } } } return list2; }
/** * 获取list 集合重复元素 * * @param list * @param <E> * @return */ public static <E> List<E> getDuplicateElements(List<E> list) { return list.stream() .filter( i -> i!="") // list 对应的 Stream 并过滤"" .collect(Collectors.toMap(e -> e, e -> 1, Integer::sum)) // 获得元素出现频率的 Map,键为元素,值为元素出现的次数 .entrySet() .stream() // 所有 entry 对应的 Stream .filter(e -> e.getValue() > 1) // 过滤出元素出现次数大于 1 (重复元素)的 entry .map(Map.Entry::getKey) // 获得 entry 的键(重复元素)对应的 Stream .collect(Collectors.toList()); // 转化为 List }
转自:(3条消息) 获取list集合中重复的元素_妃宫千早的博客-CSDN博客_list获取重复数据
标签:List,元素,list,results,获取,words,集合,entry 来源: https://www.cnblogs.com/wwssgg/p/16349501.html