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);
打印结果如下:
2、for 双循环去重
@Test void contextLoads3() { List<String> oldList = new ArrayList<>(); oldList.add("张三"); oldList.add("张三"); oldList.add("李四"); oldList.add("王五"); oldList.add("赵六"); for (int i = 0; i < oldList.size() - 1; i++) { for (int j = oldList.size() - 1; j>1 ; j--) { if (oldList.get(j).equals(oldList.get(i))) { oldList.remove(j); } } } System.out.println("原本的集合原素"+oldList); }
打印结果如下:
3、for 双循环重复坐标去重
@Test void 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); }
打印结果如下:
4、Set去重
@Test void 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); }
打印结果如下:
5、stream流去重
@Test void 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); }
打印结果如下: