• List自定义排序


    List自定义排序我习惯根据Collections.sort重载方法来实现,下面我只实现自己习惯方式。还有一种就是实现Comparable接口。

    挺简单的,直接上代码吧。

    package com.sort;
    
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    /**
     * list自定义排序
     * @author root
     *
     */
    public class ListSort {
    	@SuppressWarnings("unchecked")
    	public static void main(String[] args) {
    		User user1 = new User();
    		user1.setName("a");
    		user1.setAge(19);
    		user1.setOrder(10);
    		User user2 = new User();
    		user2.setName("b");
    		user2.setAge(20);
    		user2.setOrder(2);
    		User user3 = new User();
    		user3.setName("c");
    		user3.setAge(20);
    		user3.setOrder(1);
    		List<User> list = new ArrayList<User>();
    		list.add(user1);
    		list.add(user2);
    		list.add(user3);
    		/*自定义按照age排序
        	Collections.sort(list,new Comparator(){
    			@Override
    			public int compare(Object o1, Object o2) {
    				 User u1 = (User)o1;
    				 User u2 = (User)o2;
    				 return u1.getAge().compareTo(u2.getAge());
    			}
    		 });*/
    		//如果age相同,再按照order排序
    		Collections.sort(list,new Comparator(){
    			@Override
    			public int compare(Object o1, Object o2) {
    				 User u1 = (User)o1;
    				 User u2 = (User)o2;
    				 int i = u1.getAge().compareTo(u2.getAge());
    				 if(i == 0){
    					 return u1.getOrder().compareTo(u2.getOrder());
    				 }
    				 return i;
    			}
    		 });
    	    for(User user : list){
    	    	System.out.println("Name:"+user.getName()+"  Age:"+user.getAge()+"  Order:"+user.getOrder());
    	    }
    	}
    }
    

     User类:

    package com.sort;
    
    public class User {
    	private String name;
    	private Integer age;
    	private Integer order;
    	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;
    	}
    	public Integer getOrder() {
    		return order;
    	}
    	public void setOrder(Integer order) {
    		this.order = order;
    	}
    	
    	
    }
  • 相关阅读:
    yaha分词
    可定制的分词库——Yaha(哑哈)分词
    共有11款Python 中文分词库开源软件
    【机器学习实验】使用朴素贝叶斯进行文本的分类
    numpy.ones_like(a, dtype=None, order='K', subok=True)返回和原矩阵一样形状的1矩阵
    numpy.zeros(shape, dtype=float, order='C')
    numpy.ones(shape, dtype=None, order='C')
    备忘录
    关于决策平面
    关于surf显示立体图,可视化分析数据
  • 原文地址:https://www.cnblogs.com/xubiao/p/5802068.html
Copyright © 2020-2023  润新知