Java List 去重
-
利用 Set的性质
public static void main(String[] args) { Set<Map> set = new HashSet<>(); List<Map> list = new LinkedList<>(); Map map1 = new HashMap(); map1.put("name","zhangsan"); Map map2 = new HashMap(); map2.put("name","zhangsan"); Map map3 = new HashMap(); map3.put("name","lisi"); list.add(map1); list.add(map2); list.add(map3); for (int i = 0; i < list.size(); i++) { set.add(list.get(i)); } set.forEach(i->{ System.out.println(i); });
-
新建一个新的List,把结果放在新的List中
public static void main(String[] args) { List<Map> newList = new ArrayList<>(); List<Map> list = new LinkedList<>(); Map map1 = new HashMap(); map1.put("name","zhangsan"); Map map2 = new HashMap(); map2.put("name","zhangsan"); Map map3 = new HashMap(); map3.put("name","lisi"); list.add(map1); list.add(map2); list.add(map3); for (int i = 0; i < list.size(); i++) { if (!newList.contains(list.get(i))){ newList.add(list.get(i)); } } newList.forEach(i->{ System.out.println(i); });