Java8 implements stream to convert the set of attributes extracted from the set of objects list into map or list

  • 2021-08-16 23:54:22
  • OfStack

First, create a new entity class Person


@Data
public class Person {
 /**  Code  */
 private String code;
 /**  Name  */
 private String name;
 public Person(String code, String name) {
  this.code = code;
  this.name = name;
 }
}

Instantiate 3 objects into the list collection


public static void main(String[] args) {
 Person person1 = new Person("001", " Zhang 3");
 Person person2 = new Person("002", " Li 4");
 Person person3 = new Person("002", " Wang 5");
 List<Person> personList = new ArrayList<>();
 personList.add(person1);
 personList.add(person2);
 personList.add(person3);
 personList.forEach(t -> System.out.println(t.toString()));
}

The output is:

Person (code=001, name=Zhang 3)

Person (code=002, name=Li 4)

Person (code=002, name=Wang 5)

1. Extract code of the object as key, name as value and convert it into map set

The method is


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

The filter () method filters out objects whose names are null. When the object's name is null, an NPE null pointer exception occurs

(k1,k2)- > k2 means the second value when the same key is encountered

(k1,k2)- > k1 means to take the first value when the same key is encountered

Call this method


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

The output is:

001-Zhang 3

002-Wang 5

2. Extract the name of the object to get the list set of name

The method is


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

Call this method


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

The output is:

Zhang 3

Lee 4

Wang 5

Additional: java8 uses stream to convert List to Map, or to get a single attribute List from an List object, which is sorted by a field in List

1. Students


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

2. Test classes


public class Test {
 public static void main(String[] args) {
 
  //  Create students List
  List<Student> list = createStudentList();
 
  // 1. Get value For Student Object, key For students ID Adj. Map
  getStudentObjectMap(list);
 
  // 2. Get value Is the student's name, key For students ID Adj. Map
  getStudentNameMap(list);
 
  // 3. Get student name List
  getStudentNameList(list);
 
  //4.List Delete students from id = 1 Object of 
 
  list.removeIf(student -> student.getStuId().equals(1));
 
  //5. If StudentId For Long How to change the type? 
 
  Map<String, String> mapStr = list.stream().collect(Collectors.toMap(student -> student.getStuId().toString(), student -> JSON.toJSONString(student)));
 
  //6. According to List Medium Student Sort student names for 
  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 Traversal 
  List<String> listStr = new ArrayList<>(); 
  List<Student> listStu = new ArrayList<>(); 
  listStr.forEach(studentStr -> { 
   listStu.add(JSON.parseObject(studentStr, Student.class));
 
  });
 
  //List Filter and sort according to a field 
  listStu.stream()
    .filter(student -> student.getSex().equals(" Female "))
    .sorted(Comparator.comparing(Student::getName))
    .collect(Collectors.toList());
 
  //List Group by a field 
  Map<String,List<Student>> sexGroupMap = listStu.stream()
              .collect(Collectors.groupingBy(Student::getSex));
  // If Map If more than one name is the same in the studentId Spaced by commas 
  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(" Female ");
  Student xiaoming = new Student();
  xiaoming.setStuId("2");
  xiaoming.setName("xiaoming");
  xiaoming.setAge("15");
  xiaoming.setSex(" Male ");
  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;
 }
}

Related articles: