目录
待去重列表
java
// 列表
List<String> list = new ArrayList<>();
list.add("Tom");
list.add("Jack");
list.add("Steve");
list.add("Tom");
System.out.println(list);
// [Tom, Jack, Steve, Tom]
HashSet去重(不保证顺序)
java
// 去重
Set<String> set = new HashSet<>(list);
List<String> newList = new ArrayList<>(set);
System.out.println(newList);
// [Tom, Steve, Jack]
TreeSet去重(不保证顺序)
java
// 去重
Set<String> set = new TreeSet<>(list);
List<String> newList = new ArrayList<>(set);
System.out.println(newList);
// [Jack, Steve, Tom]
LinkedHashSet去重(保证顺序)
java
// 去重
Set<String> set = new LinkedHashSet<>(list);
List<String> newList = new ArrayList<>(set);
System.out.println(newList);
// [Tom, Jack, Steve]
遍历List去重(保证顺序)
java
// 去重
List<String> newList = new ArrayList<>();
for (String value : list) {
if(!newList.contains(value)){
newList.add(value);
}
}
System.out.println(newList);
// [Tom, Jack, Steve]
Java8中Stream流处理(保证顺序)
java
// 去重
List<String> newList = list.stream().distinct().collect(Collectors.toList());
System.out.println(newList);
// [Tom, Jack, Steve]