An instance of Java sorted by a field of an object stored in List

  • 2020-05-19 04:56:11
  • OfStack

Key points: implement the Comparable class with objects stored in List and override its compareTo () method

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 Xiao Ming ",11);
		stuList.add(stu);
		
		stu=new StuVo("2","d The bear ",15);
		stuList.add(stu);
		
		stu=new StuVo("3","a zhang 3",10);
		stuList.add(stu);
		
		stu=new StuVo("4","b li 4",15);
		stuList.add(stu);
	
		Collections.sort(stuList);
		
		Iterator<StuVo> it =stuList.iterator();
		while(it.hasNext()){
			System.out.println(it.next().getName());
		}
	}
}

Related articles: