HashSet去除List重复元素
使用Hashset 去重复
例一,List<String> 去重复
public class main { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("李菊福"); list.add("狗娃"); list.add("尼古拉斯赵四"); list.add("尼古拉斯赵四"); list.add("尼古拉斯赵四"); list.add("刘能"); list.add("刘能"); list.add("阿里郎"); System.out.println("排序前"); for (String string : list) { System.out.println(string); }
//排序 HashSet h = new HashSet(list); list.clear(); list.addAll(h);
System.out.println("排序后"); for (String string : list) { System.out.println(string); } } }
打印结果
-----去重前---- 李菊福 狗娃 尼古拉斯赵四 尼古拉斯赵四 尼古拉斯赵四 刘能 刘能 阿里郎 -------去重后-------- 狗娃 李菊福 阿里郎 尼古拉斯赵四 刘能
例二,List<Map<String,String>> 去重复
public static void main(String[] args) { List<Map<String,String>> list = new ArrayList(); Map<String,String> map1 = new HashMap<String, String>(); Map<String,String> map2 = new HashMap<String, String>(); Map<String,String> map3 = new HashMap<String, String>(); Map<String,String> map4 = new HashMap<String, String>(); Map<String,String> map5 = new HashMap<String, String>(); Map<String,String> map6 = new HashMap<String, String>(); Map<String,String> map7 = new HashMap<String, String>(); map1.put("custName","shoes"); map1.put("productId","1"); map2.put("custName","shoes"); map2.put("productId","2"); map3.put("custName","hat"); map3.put("productId","3"); map4.put("custName","hat"); map4.put("productId","3"); map5.put("custName","shoes"); map5.put("productId","2"); map6.put("custName","clothes"); map6.put("productId","2"); map7.put("custName","clothesSample"); map7.put("productId","2"); list.add(map1); list.add(map2); list.add(map3); list.add(map4); list.add(map5); list.add(map6); list.add(map7); System.out.println("去重前"); for (Map<String,String> map : list) { System.out.println(map.get("custName")+ " : " +map.get("productId")); } //去重 HashSet h = new HashSet(list); list.clear(); list.addAll(h); System.out.println("-----"); System.out.println("去重后"); for (Map<String,String> map : list) { System.out.println(map.get("custName")+ " : " +map.get("productId")); } }
打印
去重前 shoes : 1 shoes : 2 hat : 3 hat : 3 shoes : 2 clothes : 2 clothesSample : 2 ----- 去重后 clothes : 2 shoes : 2 clothesSample : 2 shoes : 1 hat : 3