目录
1、for循环添加去重
2、for 双循环去重
3、for 双循环重复坐标去重
4、Set去重
5、stream流去重
1、for循环添加去重
List<String> oldList = new ArrayList<>();oldList.add("张三");oldList.add("张三");oldList.add("李四");oldList.add("王五");oldList.add("赵六");List<Object> newList = Lists.newArrayList();for (String name : oldList) {if (!newList.contains(name)){newList.add(name);}}System.out.println("原本的集合原素"+oldList);System.out.println("去重后的集合"+newList);// An highlighted block
var foo = 'bar';
打印结果如下:
2、for 双循环去重
@Testpublic void test77() {List<String> oldList = new ArrayList<>();oldList.add("张三");oldList.add("张三");oldList.add("李四");oldList.add("王五");oldList.add("赵六");for (int i = 0; i < oldList.size(); i++) {for (int j = oldList.size() - 1; j > i; j--) {if (oldList.get(j).equals(oldList.get(i))) {oldList.remove(j);}}}System.out.println("原本的集合元素:" + oldList);}}
打印结果如下:
3、for 双循环重复坐标去重
@Testvoid contextLoads4() {List<String> oldList = new ArrayList<>();oldList.add("张三");oldList.add("张三");oldList.add("李四");oldList.add("王五");oldList.add("赵六");List<String> newList = Lists.newArrayList();newList.addAll(oldList);for (String name : newList) {if (oldList.indexOf(name) != oldList.lastIndexOf(name)) {oldList.remove(oldList.lastIndexOf(name));}}System.out.println("原本的集合原素"+oldList);}// An highlighted block
var foo = 'bar';
打印结果如下:
4、Set去重
@Testvoid contextLoads5() {List<String> oldList = new ArrayList<>();oldList.add("张三");oldList.add("张三");oldList.add("李四");oldList.add("王五");oldList.add("赵六");List<String> newList = Lists.newArrayList(new HashSet(oldList));System.out.println("原本的集合原素"+newList);}// An highlighted block
var foo = 'bar';
打印结果如下:
5、stream流去重
@Testvoid contextLoads5() {List<String> oldList = new ArrayList<>();oldList.add("张三");oldList.add("张三");oldList.add("李四");oldList.add("王五");oldList.add("赵六");List<String> collect = oldList.stream().distinct().collect(Collectors.toList());System.out.println("原本的集合原素"+collect);}// An highlighted block
var foo = 'bar';
打印结果如下: