一、list转map:
public Map<Long, String> getIdNameMap(List<Account> accounts) { return accounts.stream().collect(Collectors.toMap(Account::getId, Account::getUsername));}
public Map<Long, Account> getIdNameMap(List<Account> accounts) { return accounts.stream().collect(Collectors.toMap(Account::getId, account --> account));}
二、从对象集合中取出某个字段的集合�
//定义list集合List<P> list = Arrays.asList(new P(1, "哈哈"), new P(2, "嘿嘿"), new P(3, "呵呵"));//从list集合中,取出字段name的列表List<String> names = list.stream().map(p -> p.getName()).collect(Collectors.toList());
三、使用filter()过滤List
//测试数据,请不要纠结数据的严谨性List<StudentInfo> studentList = new ArrayList<>();studentList.add(new StudentInfo("李小明",true,18,1.76,LocalDate.of(2001,3,23)));studentList.add(new StudentInfo("张小丽",false,18,1.61,LocalDate.of(2001,6,3)));studentList.add(new StudentInfo("王大朋",true,19,1.82,LocalDate.of(2000,3,11)));studentList.add(new StudentInfo("陈小跑",false,17,1.67,LocalDate.of(2002,10,18)));StudentInfo.printStudents(studentList);//查找身高在1.8米及以上的男生List<StudentInfo> boys = studentList.stream().filter(s->s.getGender() && s.getHeight() >= 1.8).collect(Collectors.toList());//输出查找结果StudentInfo.printStudents(boys);