publicstaticvoidmain(String[] args){ User user1 = new User(5, "aa"); User user2 = new User(2, "ba"); User user3 = new User(3, "ac"); User user4 = new User(1, "aad"); User user5 = new User(4, "asd"); // Arrays.asList()返回一个固定长度的List,不能使用流式删除集合中的元素 // https://stackoverflow.com/questions/43020075/java-util-arrays-aslist-when-used-with-removeif-throws-unsupportedoperationexcep //List<User> userList = Arrays.asList(user1, user2, user3, user4, user5); List<User> userList = new ArrayList<>(); userList.add(user1);userList.add(user2);userList.add(user3);userList.add(user4);userList.add(user5);
Iterator<User> userIterator = userList.iterator(); while (userIterator.hasNext()) { Integer checkId = userIterator.next().getId(); if (checkId > 3) { userIterator.remove(); } }
而在 Java 8 提供的流式计算中,可以使用 Collection.removeIf() API 很方便的删除某个元素:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
publicstaticvoidmain(String[] args){ User user1 = new User(5, "aa"); User user2 = new User(2, "ba"); User user3 = new User(3, "ac"); User user4 = new User(1, "aad"); User user5 = new User(4, "asd"); // Arrays.asList()返回一个固定长度的List,不能使用流式删除集合中的元素 // https://stackoverflow.com/questions/43020075/java-util-arrays-aslist-when-used-with-removeif-throws-unsupportedoperationexcep //List<User> userList = Arrays.asList(user1, user2, user3, user4, user5); List<User> userList = new ArrayList<>(); userList.add(user1);userList.add(user2);userList.add(user3);userList.add(user4);userList.add(user5);
publicstaticvoidmain(String[] args){ // User{id, name, clazzId} User user1 = new User(1, "aa", 100); User user2 = new User(1, "aa", 200); User user3 = new User(2, "bb", 100); List<User> userList = new ArrayList<>(); userList.add(user1);userList.add(user2);userList.add(user3);
Map<Integer, List<User>> userId2UserClazzsMap = new HashMap<>(); for (User user : userList) { if (userId2UserClazzsMap.get(user.getId()) == null) { List<User> userSet = new ArrayList<>(); userSet.add(user); userId2UserClazzsMap.put(user.getId(), userSet); } else { List<User> userSet = userId2UserClazzsMap.get(user.getId()); userSet.add(user); userId2UserClazzsMap.put(user.getId(), userSet); } } userId2UserClazzsMap.forEach((key, value) -> System.out.println(key + "---" + value.size())); }
而在 Java 8 中,我们可以很方便的使用 Collectors.groupingBy() API 来实现相同功能:
1 2 3 4 5 6 7 8 9 10 11
publicstaticvoidmain(String[] args){ // User{id, name, clazzId} User user1 = new User(1, "aa", 100); User user2 = new User(1, "aa", 200); User user3 = new User(2, "bb", 100); List<User> userList = new ArrayList<>(); userList.add(user1);userList.add(user2);userList.add(user3);