/** * map遍历 * @Author: Mr.li * @Date: 2020/9/8 */ @Test public void demo() { List<Person> list = new ArrayList<>(); for (int i = 0; i < 100; i++) { Person person = new Person(); person.setId((int) (Math.random() * 10)); person.setName("你不知" + i); list.add(person); } Map<Integer, List<Person>> map = list .stream() .collect(Collectors.groupingBy(Person::getId)); System.out.println(map); map.forEach((k, v) -> System.out.println("key:value = " + k + ":" + v)); map.forEach((k, v) -> { String idStr = v.stream().map(obj -> obj.getId().toString()).collect(Collectors.joining(",")); String nameStr = v.stream().map(obj -> obj.getName()).collect(Collectors.joining(",")); System.out.println(idStr); System.out.println(nameStr); }); List<User> userList = new ArrayList<User>() { { add(new User("a", "1993/12/24", 26)); add(new User("b", "1973/12/24", 46)); add(new User("c", "1995/12/24", 24)); add(new User("a", "1981/12/24", 38)); add(new User("a", "1991/12/24", null)); } }; Map<String, Integer> nameMap = userList.stream() .filter(e -> e.getAge() != null)//过滤掉空的数据 .collect(Collectors.toMap(User::getName, User::getAge, (value1, value2) -> value2)); System.out.println(nameMap); }
result: