To process duplicate values in the list collection, most of them use two methods. One is to traverse the list collection and then assign it to another list collection, and the other is to use Assigned to the set collection and returned to the list collection. Different methods have their own advantages in different situations.
Related free video tutorial recommendations: java free video tutorial
The code is as follows:
//set集合去重,不打乱顺序 public static void main(String[] args){ List<String> list = new ArrayList<String>(); list.add("aaa"); list.add("bbb"); list.add("aaa"); list.add("aba"); list.add("aaa"); Set set = new HashSet(); List newList = new ArrayList(); for (String cd:list) { if(set.add(cd)){ newList.add(cd); } } System.out.println( "去重后的集合: " + newList); }
//遍历后判断赋给另一个list集合 public static void main(String[] args){ List<String> list = new ArrayList<String>(); list.add("aaa"); list.add("bbb"); list.add("aaa"); list.add("aba"); list.add("aaa"); List<String> newList = new ArrayList<String>(); for (String cd:list) { if(!newList.contains(cd)){ newList.add(cd); } } System.out.println( "去重后的集合: " + newList); }
//set去重 public static void main(String[] args){ List<String> list = new ArrayList<String>(); list.add("aaa"); list.add("bbb"); list.add("aaa"); list.add("aba"); list.add("aaa"); Set set = new HashSet(); List newList = new ArrayList(); set.addAll(list); newList.addAll(set); System.out.println( "去重后的集合: " + newList); }
//set去重(缩减为一行) public static void main(String[] args){ List<String> list = new ArrayList<String>(); list.add("aaa"); list.add("bbb"); list.add("aaa"); list.add("aba"); list.add("aaa"); List newList = new ArrayList(new HashSet(list)); System.out.println( "去重后的集合: " + newList); }
hashset does not sort, and another method is to use treeset , remove duplicates and arrange them in natural order, just change hashset to treeset. (The original order has been changed, just arranged in alphabetical order)
//去重并且按照自然顺序排列 List newList = new ArrayList(new TreeSet(list));
More related articles and tutorials are recommended: Java zero-based introduction
The above is the detailed content of How to prevent duplicate elements in list collection in java. For more information, please follow other related articles on the PHP Chinese website!