下面有5 种去除List重复元素的方法:
- for 循环添加去重
- for 双循环去重
- for 循环重复坐标去重
- Set 去重
- Stream 去重
1 for循环添加去重
package com.example.demo.controller;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class listtest2 {
public static List<String> initList = Arrays.asList(
"张三",
"李四",
"张三",
"周一",
"刘四",
"李强",
"李白",
"张三",
"李强",
"王五"
);
public static void main(String[] args) {
List<String> list = new ArrayList(initList);
List<String> list2 = new ArrayList<>();
for (String element : list) {
if (!list2.contains(element)) {
list2.add(element);
}
}
System.out.println(list2);
}
}
这个是最基本的实现了,创建一个空的 List,添加前判断一下存在不存在,不存在才添加,这样就保证了元素不重复。
2 for双循环去重
package com.example.demo.controller;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class listtest2 {
public static List<String> initList = Arrays.asList(
"张三",
"李四",
"张三",
"周一",
"刘四",
"李强",
"李白",
"张三",
"李强",
"王五"
);
public static void main(String[] args) {
List<String> list = new ArrayList(initList);
for (int i = 0; i < list.size() - 1; i++) {
for (int j = list.size() - 1; j > i; j--) {
if (list.get(j).equals(list.get(i))) {
list.remove(j);
}
}
}
System.out.println(list);
}
}
利用双循环,判断是否有相等的,再进行移除。
3 for循环重复坐标去重
package com.example.demo.controller;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class listtest2 {
public static List<String> initList = Arrays.asList(
"张三",
"李四",
"张三",
"周一",
"刘四",
"李强",
"李白",
"张三",
"李强",
"王五"
);
public static void main(String[] args) {
List<String> list = new ArrayList(initList);
List<String> list2 = new ArrayList(initList);
for (String element : list2) {
if (list.indexOf(element) != list.lastIndexOf(element)) {
list.remove(list.lastIndexOf(element));
}
}
System.out.println(list);
}
}
复制一个 list2,再循环 List2,判断 list 中的元素的首尾出现的坐标位置是否一致,如果一致,则说明没有重复的,否则重复,再删除重复的位置的元素。
4 Set去重
package com.example.demo.controller;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
public class listtest2 {
public static List<String> initList = Arrays.asList(
"张三",
"李四",
"张三",
"周一",
"刘四",
"李强",
"李白",
"张三",
"李强",
"王五"
);
public static void main(String[] args) {
List<String> list = new ArrayList(initList);
List<String> list2 = new ArrayList(new HashSet(list));
System.out.println(list2);
}
}
我们知道 Set 是不包含重复元素的,把 List 先装进 HashSet,然后再装回来,这样就保证了元素的不重复。
5 Stream去重
package com.example.demo.controller;
import java.util.*;
import java.util.stream.Collectors;
public class listtest2 {
public static List<String> initList = Arrays.asList(
"张三",
"李四",
"张三",
"周一",
"刘四",
"李强",
"李白",
"张三",
"李强",
"王五"
);
public static void main(String[] args) {
List<String> list = new ArrayList(initList);
list = list.stream().distinct().collect(Collectors.toList());
System.out.println(list);
}
}
利用 Stream 的 distinct 方法去重,这个方法也十分简单,一行代码搞定