Java Map集合 转化为List 并为List排序

来源:互联网 发布:闪电下单软件 编辑:程序博客网 时间:2024/06/07 11:18
public class MapToList {public static void main(String[] args) {List<Student> studentList = new ArrayList<Student>();//添加20个学生姓名和学号for (int i=0;i<20;i++){Student student = new Student();student.setStudentName("张三"+(i+1));student.setStudentNO((i+1));studentList.add(student);}//获取Map K-V 类型 对象Map<String,String> resultMap = List_ToMap(studentList);//获取List 对象List<Student> resultList =  Map_ToList( resultMap);        for (Student s : resultList)        {        System.out.println(s.getStudentNO() +"\t"+s.getStudentName());        }}<strong>//List转换为Mappublic static Map<String,String> List_ToMap(List<Student> resultList){Map<String,String> resultMap = new HashMap<>();//获取参数值List<Student> list = resultList;if (list.size() == 0 ){return resultMap;}//遍历集合for (Student stu : list ){resultMap.put(String.valueOf(stu.getStudentNO()), stu.getStudentName());}return resultMap;}</strong>//Map类型转换为Listpublic static List<Student>  Map_ToList(Map<String,String> resultMap){List<Student> resultList = new ArrayList<>();Map<String,String> map = resultMap;//如果为空直接返回 空对象if (map.size() == 0){return resultList;}<span style="color:#ff6666;">Set<Entry<String,String>>  setEntry = map.entrySet();Iterator<Entry<String, String>> it = setEntry.iterator();while(it.hasNext()){Entry<String, String> entry = it.next();Student student = new Student();student.setStudentNO(Integer.parseInt(entry.getKey()));            student.setStudentName(entry.getValue());            resultList.add(student);}</span>//返回结果集 (并排序 )<span style="color:#ff9900;">Comparator<Student> c = new Comparator<Student>() {@Overridepublic int compare(Student o1, Student o2) {if (o1.getStudentNO() > o2.getStudentNO()){return 1;}else{return -1;}}};resultList.sort(c);</span>return resultList;}}


1 0
原创粉丝点击