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;
 }
}

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。如有錯誤或未考慮完全的地方,望不吝賜教。

推薦閱讀: