故意强调了优雅,所以双循环什么的就别来了..先谢为敬
如果你用上了 Java8,使用 Stream 来实现这个功能(getDuplicateElements
方法)会很优雅:
public class DemoCode {
public static void main(String[] args) {
List<String> list = Arrays.asList("a", "b", "c", "d", "a", "a", "d", "d");
List<String> duplicate = getDuplicateElements(list);
System.out.println("list 中重复的元素:" + duplicate);
}
public static <E> List<E> getDuplicateElements(List<E> list) {
return list.stream() // 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
}
}
运行结果:
List<String> list = new ArrayList<String>();
list.add("aaa");
list.add("bbb");
list.add("ccc");
list.add("ddd");
list.add("aaa");
list.add("aaaa");
list.add("eee");
list.add("bbb");
list.add("ccc");
StringBuilder builder = new StringBuilder();
for(String str : list) {
// 如果不存在返回 -1。
if(builder.indexOf(","+str+",") > -1) {
System.out.println("重复的有:"+str);
} else {
builder.append(",").append(str).append(",");
}
}
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);
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);
List<String> words = Arrays.asList("a", "b", "c", "d", "a", "d");
Set<String> repeated = new HashSet<>();
List<String> results = new ArrayList<>();
for (String word : words) {
if (!repeated.add(word)) {
results.add(word);
}
}
System.out.println(results);
试试小弟这个吧,简洁好用
不需要转map判断 :)
list.stream().filter(i -> list.stream().filter(i::equals).count()>1).collect(Collectors.toSet());
List<String> originList; //初始化和判空不写了
List<String> distinctList = originList.stream().distinct().collect(Collectors.toList()).size()
if(originList.size() != distinctList.size()){
//存在重复元素
}
//multiSet允许重复,并且可以求某个元素重复个数
ArrayList arrayList = Lists.newArrayList("1","2","2","3","4","1");
HashMultiset set = HashMultiset.create(arrayList);
//求出哪个重复元素
Set obj = (Set)set.stream().filter(d->set.count(d)>1).collect(Collectors.toSet());
System.out.println(obj);
3 回答2.6k 阅读✓ 已解决
3 回答4.1k 阅读✓ 已解决
8 回答3.6k 阅读
4 回答2.7k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
3 回答2.5k 阅读✓ 已解决
3 回答1.7k 阅读✓ 已解决
可以参考: