集合复习list to map

版权声明:未经博主同意,禁止转载 https://blog.csdn.net/weixin_42130471/article/details/83152106
package listtomap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class listtomap {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Map<Integer,String> map=listtomap();
		Set<Entry<Integer,String>> entryset=map.entrySet();
		Iterator<Entry<Integer,String>> it=entryset.iterator();
		while(it.hasNext()) {
			Entry<Integer,String> entry=it.next();
			System.out.println(entry);
		}
	}
	public static Map<Integer,String> listtomap() {
		Student stu1=new Student(1,"zhangsan",22);
		Student stu2=new Student(2,"lisi",24);
		Student stu3=new Student(3,"zhaowu",23);
		Student stu4=new Student(4,"wanba",22);
		List<Student> list=new ArrayList<>();
		list.add(stu1);
		list.add(stu2);
		list.add(stu3);
		list.add(stu4);
		for(int i=0;i<list.size();i++) {
			System.out.println(list.get(i));
		}
		System.out.println(list);
		Map<Integer,String> map=new HashMap<Integer,String>();
		for(Student st:list) {
			map.put(st.getSno(),st.getName());
		}
		return map;
		
	}
}

Student 类:

package listtomap;

public class Student implements Comparable<Student>{
	private int sno;
	private String name;
	private int age;
	
	public Student(int sno, String name, int age) {
		super();
		this.sno = sno;
		this.name = name;
		this.age = age;
	}

	@Override
	public String toString() {
		return "Student [sno=" + sno + ", name=" + name + ", age=" + age + "]";
	}

	public int getSno() {
		return sno;
	}

	public void setSno(int sno) {
		this.sno = sno;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

	@Override
	public int compareTo(Student arg0) {
		// TODO Auto-generated method stub
		if(this.age==arg0.age) {
			return this.sno-arg0.sno;
		}else {
			return this.age-arg0.age;
		}
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_42130471/article/details/83152106
今日推荐