Java 合并两个对象数组List并按照对象中某个字段排序(比如按照id的升降序)

2021/9/14 20:05:19

本文主要是介绍Java 合并两个对象数组List并按照对象中某个字段排序(比如按照id的升降序),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Java 合并两个对象数组List并按照对象中某个字段排序(比如按照id的升降序):

public static void main(String[] args) {
        List<YourObjectPO> yourObjectPOs1 = new ArrayList<>();
        YourObjectPO r1 = new YourObjectPO();
        r1.setInsertTime(1544326153000L);//12-9
        r1.setAlias("r1");
        YourObjectPO r2 = new YourObjectPO();
        r2.setInsertTime(1544585353000L);//12-12
        r2.setAlias("r2");
 
        yourObjectPOs1.add(r1);
        yourObjectPOs1.add(r2);
 
        List<YourObjectPO> yourObjectPOs2 = new ArrayList<>();
 
        YourObjectPO r3 = new YourObjectPO();
        r3.setInsertTime(1544498953000L);//12-11
        r3.setAlias("r3");
        YourObjectPO r4 = new YourObjectPO();
        r4.setInsertTime(1544412553000L);//12-10
        r4.setAlias("r4");
 
        YourObjectPO r5 = new YourObjectPO();
        r5.setInsertTime(1544412553000L);//12-10
        r5.setAlias("r5");
 
        yourObjectPOs2.add(r3);
        yourObjectPOs2.add(r4);
        yourObjectPOs2.add(r5);
        List<YourObjectPO> compareList = new ArrayList<>();
        compareList.addAll(yourObjectPOs1);
        compareList.addAll(yourObjectPOs2);
        Collections.sort(compareList,new Comparator<YourObjectPO>(){
            @Override
            public int compare(YourObjectPO arg0, YourObjectPO arg1) {
                int count = (int) ( arg1.getInsertTime()-arg0.getInsertTime());
                if (count == 0){
                    return 0;
                }
                if (count > 0){
                    return 1;
                }
 
                return  -1 ;
            };
        });
 
        for(YourObjectPO stu : compareList){
            System.out.println("alias------>:"+stu.getxxx()+"insertTime------->"+stu.getInsertTime());
        }
    }

最后 如果两个时间相同还要根据 具体内容排序 可以count= 0时继续排序



这篇关于Java 合并两个对象数组List并按照对象中某个字段排序(比如按照id的升降序)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程