[Java][Stream]Collectors.toMap()介紹、範例

Table of Contents

介紹

Collectors類別的toMap方法是一種整理方式,讓使用者可以把List<Object>整理成一個以某個欄位當作Key的Map

範例

public static void main(String[] args) {
		List<People> peopleList = new ArrayList<>();
		People people = new People();
		people.setName("Roy");
		people.setGender("Man");
		People people1 = new People();
		people1.setName("Peggy");
		people1.setGender("Woman");
		peopleList.add(people);
		peopleList.add(people1);
		// List轉換成Map
		Map<String, String> nameToGenderMap = peopleList.stream()
				.collect(Collectors.toMap(People::getName, People::getGender));
		for(String name : nameToGenderMap.keySet()) {
			String gender = nameToGenderMap.get(name);
			System.out.println("姓名:" + name +",性別:" + gender);
		}
	}
// 印出結果
// 姓名:Peggy,性別:Woman
// 姓名:Roy,性別:Man

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *