使用JDK8的lambda方式把List轉成Map

一、建立一個實體類(學生類)
 java

public class Student {
	private Integer id;
	private String name;
	private Integer age;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
	
}

二、建立一個測試類
 ide

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class TestDemo {
     public static void main(String[] args) {

                Student student1 = new Student();
		student1.setId(110);
		student1.setName("李明");
		student1.setAge(23);
		
		Student student2 = new Student();
		student2.setName("明浩");
		student2.setId(119);
		student2.setAge(24);
		
		List<Student> list = Lists.newArrayList();
		list.add(student1);
		list.add(student2);

                Map<Integer, Student> studentMap = list.stream().collect(Collectors.toMap(Student:: getId, (k) -> k));
		
		System.out.println("根據學號查找學生:"+studentMap.get(110).getName());
     }
}
相關文章
相關標籤/搜索