Java8 实现stream将对象集合list中抽取属性集合转化为map或list

 更新时间:2021年02月04日 15:13:21   作者:文耀文耀  
这篇文章主要介绍了Java8 实现stream将对象集合list中抽取属性集合转化为map或list的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

首先新建一个实体类Person

@Data
public class Person {
 /** 编码 */
 private String code;
 /** 名字 */
 private String name;
 public Person(String code, String name) {
  this.code = code;
  this.name = name;
 }
}

实例化三个对象放入list集合中

public static void main(String[] args) {
 Person person1 = new Person("001", "张三");
 Person person2 = new Person("002", "李四");
 Person person3 = new Person("002", "王五");
 List<Person> personList = new ArrayList<>();
 personList.add(person1);
 personList.add(person2);
 personList.add(person3);
 personList.forEach(t -> System.out.println(t.toString()));
}

输出结果为:

Person(code=001, name=张三)

Person(code=002, name=李四)

Person(code=002, name=王五)

1.抽取对象的code作为key,name作为value转化为map集合

方法为

private static HashMap<String, String> listToMap(List<Person> personList) {
 return (HashMap<String, String>)personList.stream()
   .filter(t -> t.getName()!=null)
   .collect(Collectors.toMap(Person::getCode,Person::getName,(k1,k2)->k2));
}

filter() 方法作用是过滤掉名字为空的对象,当对象的名字为null时,会出现NPE空指针异常

(k1,k2)->k2 意思是遇到相同的key时取第二个值

(k1,k2)->k1 意思是遇到相同的key时取第一个值

调用这个方法

HashMap<String,String> personMap = listToMap(personList);
personMap.forEach((k,v)-> System.out.println(k.toString() + " - " + v.toString()));

输出结果为:

001 - 张三

002 - 王五

2.抽取对象的name得到name的list集合

方法为

private static List<String> getNameList(List<Person> personList) {
 return personList.stream().map(Person::getName).collect(Collectors.toList());
}

调用这个方法

List<String> nameList = getNameList(personList);
nameList.forEach(t -> System.out.println(t.toString()));

输出结果为:

张三

李四

王五

补充:java8 使用stream将List转成Map,或者从List对象中获取单个属性List,List中根据某个字段排序

1.学生类

import lombok.Data; 
@Data
public class Student{ 
 private String stuId; 
 private String name; 
 private String age; 
 private String sex; 
}

2.测试类

public class Test {
 public static void main(String[] args) {
 
  // 创建学生List
  List<Student> list = createStudentList();
 
  // 1.获取value为Student对象,key为学生ID的Map
  getStudentObjectMap(list);
 
  // 2.获取value为学生姓名,key为学生ID的Map
  getStudentNameMap(list);
 
  // 3.获取学生姓名List
  getStudentNameList(list);
 
  //4.List中删除学生id = 1的对象
 
  list.removeIf(student -> student.getStuId().equals(1));
 
  //5.如果StudentId为Long类型如何转?
 
  Map<String, String> mapStr = list.stream().collect(Collectors.toMap(student -> student.getStuId().toString(), student -> JSON.toJSONString(student)));
 
  //6.根据List中Student的学生姓名排序
  Collections.sort(list, (o1, o2) -> {
   if (o1.getName().compareTo(o2.getName()) > 0) {
    return 1;
   } else if (o1.getName().compareTo(o2.getName()) < 0) {
    return -1;
   } else {
    return 0;
   }
  });
  //7.List遍历
  List<String> listStr = new ArrayList<>(); 
  List<Student> listStu = new ArrayList<>(); 
  listStr.forEach(studentStr -> { 
   listStu.add(JSON.parseObject(studentStr, Student.class));
 
  });
 
  //List根据某个字段过滤、排序
  listStu.stream()
    .filter(student -> student.getSex().equals("女"))
    .sorted(Comparator.comparing(Student::getName))
    .collect(Collectors.toList());
 
  //List根据某个字段分组
  Map<String,List<Student>> sexGroupMap = listStu.stream()
              .collect(Collectors.groupingBy(Student::getSex));
  //如果Map中多个名称相同,则studentId用逗号间隔
  Map<String,String> studentNameIdMap = listStu.stream()
              .collect(toMap(Student::getName,Student::getStuId,(s,a)->s+","+a));
 }
 
 public static List<Student> createStudentList() {
  List<Student> list = new ArrayList<Student>();
  Student lily = new Student();
  lily.setStuId("1");
  lily.setName("lily");
  lily.setAge("14");
  lily.setSex("女");
  Student xiaoming = new Student();
  xiaoming.setStuId("2");
  xiaoming.setName("xiaoming");
  xiaoming.setAge("15");
  xiaoming.setSex("男");
  list.add(lily);
  list.add(xiaoming);
  return list;
 }
 
 public static Map<Object, Object> getStudentObjectMap(List<Student> list) {
  Map<Object, Object> map = list.stream().collect(Collectors.toMap(Student::getStuId, student -> student));
  map.forEach((key, value) -> {
   System.out.println("key:" + key + ",value:" + value);
  });
  return map;
 }
 
 public static Map<String, String> getStudentNameMap(List<Student> list) {
  Map<String, String> map = list.stream().collect(Collectors.toMap(Student::getStuId, Student::getName));
  map.forEach((key, value) -> {
   System.out.println("key:" + key + ",value:" + value);
  });
  return map;
 }
 
 public static List<String> getStudentNameList(List<Student> list) {
  List<String> result = list.stream().map(student -> student.getName()).collect(Collectors.toList());
  for (String name : result) {
   System.out.println("name:" + name);
  }
  return result;
 }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。如有错误或未考虑完全的地方,望不吝赐教。

相关文章

  • java接收文件流+response.body()调用两次问题(分别接收文件和对象)

    java接收文件流+response.body()调用两次问题(分别接收文件和对象)

    这篇文章主要介绍了java接收文件流+response.body()调用两次问题(分别接收文件和对象),具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-06-06
  • nacos(SpringCloud)配置加载过程

    nacos(SpringCloud)配置加载过程

    Nacos是Spring Cloud的配置中心,通过BootstrapApplicationListener和ConfigFileApplicationListener监听器加载配置文件,并通过PropertySourceBootstrapConfiguration将Nacos配置加载到Spring Boot应用的environment中
    2024-12-12
  • Java使用POI-TL实现生成有个性的简历

    Java使用POI-TL实现生成有个性的简历

    POI-TL 是一个基于 Apache POI 的 Java 库,专注于在 Microsoft Word 文档(.docx 格式)中进行模板填充和动态内容生成,下面我们看看如何使用POI-TL生成有个性的简历吧
    2024-11-11
  • Struts2 Result 参数详解

    Struts2 Result 参数详解

    这篇文章主要讲解Struts2 Result的参数,讲的比较详细,希望能给大家做一个参考。
    2016-06-06
  • Java如何获取Date的“昨天”与“明天”示例代码

    Java如何获取Date的“昨天”与“明天”示例代码

    最近在做项目的时候用到Date和Calendar比较多,而且用到的方式也比较全,突然想到一个问题,Java如何获取Date的"昨天"与"明天",也就是前一天和后一天呢?思考后写出了方法,想着万一以后用到,就总结出来,也方便有需要的朋友们参考借鉴,下面来一起看看吧。
    2016-12-12
  • Java实现邮件发送QQ邮箱带附件

    Java实现邮件发送QQ邮箱带附件

    这篇文章主要为大家详细介绍了Java实现邮件发送QQ邮箱带附件功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-03-03
  • Java FileInputStream与FileOutputStream使用详解

    Java FileInputStream与FileOutputStream使用详解

    这篇文章主要介绍了Java FileInputStream与FileOutputStream使用详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
    2021-08-08
  • SpringBoot AOP中JoinPoint的使用方式和通知切点表达式

    SpringBoot AOP中JoinPoint的使用方式和通知切点表达式

    这篇文章主要介绍了SpringBoot AOP中JoinPoint的使用方式和通知切点表达式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-05-05
  • Java项目开发命名规范(动力节点Java学院整理)

    Java项目开发命名规范(动力节点Java学院整理)

    定义这个规范的目的是让项目中所有的文档都看起来像一个人写的,增加可读性,减少项目组中因为换人而带来的损失。下面给大家分享java开发命名规范,一起看看吧
    2017-03-03
  • SpringBoot注册web组件的实现方式

    SpringBoot注册web组件的实现方式

    Servlet是Java Web应用程序的基础,它提供了处理客户端请求的机制,Servlet三大组件是指Servlet、Filter和Listener,它们是Java Web应用程序的核心组件,本文将给大家介绍一下SpringBoot注册web组件的实现方式,需要的朋友可以参考下
    2023-10-10

最新评论