1. 創建容器對象 Person 類
import lombok.Data;
@Data
public class Person {
public Person(Long id,String name, Boolean gender, Integer age, float score) {
this.id = id;
this.name = name;
this.gender = gender;
this.age = age;
this.score = score;
}
public Person(String name, Boolean gender) {
this.name = name;
this.gender = gender;
}
private Long id;
private String name;
private Boolean gender;
private Integer age;
private float score;
}
2. 在測試方法中實現功能
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class StreamMainTest {
public static void main(String[] args) {
// 創建包含 id 的對象
Person p1 = new Person(1L, "zhangsan", false, 19, 60);
Person p2 = new Person(2L, "lisi", true, 20, 80);
Person p3 = new Person(3L, "wangmazi", false, 28, 70);
Person p4 = new Person(4L, "meiyoule", true, 15, 50);
// 創建不包含 id 的對象
Person p5 = new Person("evsd", true);
Person p6 = new Person("evsd", true);
// 將對象裝入 list 集合中
List<Person> people = Arrays.asList(p1, p2, p3, p4, p5, p6);
Map<Long, String> idAndNameMap = people.stream()
// 過濾掉 id 為空的對象
.filter(person -> (null != person.getId()))
// 將對象的 id 和 name 取出轉換成 map 集合
.collect(Collectors.toMap(Person::getId, Person::getName));
// 處理map 中 value 中有 null 的情況
Map<Long, String> idAndNameMapHasNull = people.stream().collect(HashMap::new,
(m, v)->m.put(v.getId(), v.getName()), HashMap::putAll);
// 遍歷輸出 map 集合
idAndNameMap.forEach((key, value) -> {
System.out.println(key + "--- " + value);
});
}
}
輸出效果
1--- zhangsan
2--- lisi
3--- wangmazi
4--- meiyoule
Process finished with exit code 0