• Java依照List内存储的对象的某个字段进行排序


    关键点:将List内存储的对象实现Comparable类。重写它的compareTo()方法就可以

    Bean:

    package chc;
    public class StuVo implements Comparable<StuVo>{
    	private String id;
    	private String name;
    	private Integer age;
    	public StuVo(String id, String name, Integer age) {
    		this.id=id;
    		this.name=name;
    		this.age=age;
    	}
    	public int compareTo(StuVo stu) {
    		return this.name.compareTo(stu.getName());
    	}
    	public String getId() {
    		return id;
    	}
    	public void setId(String id) {
    		this.id = id;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public Integer getAge() {
    		return age;
    	}
    	public void setAge(Integer age) {
    		this.age = age;
    	}
    }
    

    Demo:

    package chc;
    
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Iterator;
    import java.util.List;
    
    public class ArrayListSortDemo {
    	public static void main(String[] args) {
    		List<StuVo> stuList=new ArrayList<StuVo>();
    		StuVo stu=new StuVo("1","h小明",11);
    		stuList.add(stu);
    		
    		stu=new StuVo("2","d阿熊",15);
    		stuList.add(stu);
    		
    		stu=new StuVo("3","a张三",10);
    		stuList.add(stu);
    		
    		stu=new StuVo("4","b李四",15);
    		stuList.add(stu);
    	
    		Collections.sort(stuList);
    		
    		Iterator<StuVo> it =stuList.iterator();
    		while(it.hasNext()){
    			System.out.println(it.next().getName());
    		}
    	}
    }
    




  • 相关阅读:
    P1064 金明的预算方案
    P1164 小A点菜
    P1346 电车
    01背包二进制优化
    2018暑期多校1
    牛课第二次多校I
    STL
    Reachability from the Capital
    P2921 [USACO08DEC]在农场万圣节Trick or Treat on the Farm
    P3387 【模板】缩点
  • 原文地址:https://www.cnblogs.com/claireyuancy/p/6790069.html
Copyright © 2020-2023  润新知