List的五种去重方式
Posted onelikeone
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了List的五种去重方式相关的知识,希望对你有一定的参考价值。
//set集合去重,不改变原有的顺序 public static void pastLeep1(List<String> list){ System.out.println("list = [" + list.toString() + "]"); List<String> listNew=new ArrayList<>(); Set set=new HashSet(); for (String str:list) { if(set.add(str)){ listNew.add(str); } } System.out.println("listNew = [" + listNew.toString() + "]"); } //遍历后判断赋给另一个list集合 public static void pastLeep2(List<String> list){ System.out.println("list = [" + list.toString() + "]"); List<String> listNew=new ArrayList<>(); for (String str:list) { if(!listNew.contains(str)){ listNew.add(str); } } System.out.println("listNew = [" + listNew.toString() + "]"); } //set去重 public static void pastLeep3(List<String> list){ System.out.println("list = [" + list + "]"); Set set = new HashSet(); List<String> listNew=new ArrayList<>(); set.addAll(list); listNew.addAll(set); System.out.println("listNew = [" + listNew + "]"); } //set去重(缩减为一行) public static void pastLeep4(List<String> list){ System.out.println("list = [" + list + "]"); List<String> listNew=new ArrayList<>(new HashSet(list)); System.out.println("listNew = [" + listNew + "]"); } //去重并按自然顺序排序 public static void pastLeep5(List<String> list){ System.out.println("list = [" + list + "]"); List<String> listNew=new ArrayList<>(new TreeSet<String>(list)); System.out.println("listNew = [" + listNew + "]"); }
以上是关于List的五种去重方式的主要内容,如果未能解决你的问题,请参考以下文章