一、list转map:

  1. public Map<Long, String> getIdNameMap(List<Account> accounts) {
  2. return accounts.stream().collect(Collectors.toMap(Account::getId, Account::getUsername));
  3. }
  1. public Map<Long, Account> getIdNameMap(List<Account> accounts) {
  2. return accounts.stream().collect(Collectors.toMap(Account::getId, account --> account));
  3. }

二、从对象集合中取出某个字段的集合�

  1. //定义list集合
  2. List<P> list = Arrays.asList(new P(1, "哈哈"), new P(2, "嘿嘿"), new P(3, "呵呵"));
  3. //从list集合中,取出字段name的列表
  4. List<String> names = list.stream().map(p -> p.getName()).collect(Collectors.toList());

三、使用filter()过滤List

  1. //测试数据,请不要纠结数据的严谨性
  2. List<StudentInfo> studentList = new ArrayList<>();
  3. studentList.add(new StudentInfo("李小明",true,18,1.76,LocalDate.of(2001,3,23)));
  4. studentList.add(new StudentInfo("张小丽",false,18,1.61,LocalDate.of(2001,6,3)));
  5. studentList.add(new StudentInfo("王大朋",true,19,1.82,LocalDate.of(2000,3,11)));
  6. studentList.add(new StudentInfo("陈小跑",false,17,1.67,LocalDate.of(2002,10,18)));
  7. StudentInfo.printStudents(studentList);
  8. //查找身高在1.8米及以上的男生
  9. List<StudentInfo> boys = studentList.stream().filter(s->s.getGender() && s.getHeight() >= 1.8).collect(Collectors.toList());
  10. //输出查找结果
  11. StudentInfo.printStudents(boys);