Gracefully find the duplicate elements in the ArrayList
•
Java
Method 1
/**
- Created by cxh on 17/1/9.
*/
public class Main {
public static void main(String[] args){
Listlist = new ArrayList ();
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) {
Sy stem.out.println("重复的有:"+str);
} else {
builder.append(",").append(str).append(",");
}
}
}
}
Method 2
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
/**
- Created by cxh on 17/1/9.
*/
public class Main {
public static void main(String[] args){
Listlist=new ArrayList ();
list.add("string1");
list.add("string2");
list.add("string3");
list.add("string1");
list.add("string1");
list.add("string1");
list.add("string2");
//list.add("string3");
HashMap<String,Integer> hashMap=new HashMap<String,Integer>();
for(String string:list){
if(hashMap.get(string)!=null){ //hashMap包含遍历list中的当前元素
Integer integer=hashMap.get(string);
hashMap.put(string,integer+1);
Sy stem.out.println("the element:"+string+" is repeat");
}
else{
hashMap.put(string,1);
}
}
}
}
Method 3
public class Main {
public static <E> List<E> getDuplicateElements(List<E> list) { return list.stream() // list 对应的 Stream .collect(Collectors.toMap(e -> e,e -> 1,(a,b) -> a + b)) // 获得元素出现频率的 Map,键为元素,值为元素出现的<a href="https://www.jb51.cc/tag/cishu/" target="_blank" class="keywords">次数</a> .entrySet().stream() // 所有 entry 对应的 Stream .filter(entry -> entry.getValue() > 1) // 过滤出元素出现<a href="https://www.jb51.cc/tag/cishu/" target="_blank" class="keywords">次数</a>大于 1 的 entry .map(entry -> entry.getKey()) // 获得 entry 的键(重复元素)对应的 Stream .collect(Collectors.toList()); // 转化为 List } public static void main(String[] args) throws Exception { List<String> list = Arrays.asList("a","b","c","d","a","d"); List<String> duplicateElements = getDuplicateElements(list); Sy<a href="https://www.jb51.cc/tag/stem/" target="_blank" class="keywords">stem</a>.out.println("list 中重复的元素:" + duplicateElements); }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码