List对象按其中某个属性的顺序排序

list按属性值排序

userList.sort(Comparator.comparing(Use::getNumber));

对象

package com.rpmc.demo;

public class Use {

    private int number;
    private String name;


    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

List对象

package com.rpmc.demo;

import com.crscd.pcap4j.modle.ReturnContactSubModle;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Test {

    public static void main(String[] args) {


        List<Use> userList = new ArrayList<>();
        Use use = new Use();
        use.setNumber(10);
        use.setName("小王");
        userList.add(use);

        Use use1 = new Use();
        use1.setNumber(3);
        use1.setName("小李");
        userList.add(use1);

        Use use2 = new Use();
        use2.setNumber(6);
        use2.setName("小六");
        userList.add(use2);


        Use use3 = new Use();
        use3.setNumber(2);
        use3.setName("小哎");
        userList.add(use3);

        Use use4 = new Use();
        use4.setNumber(11);
        use4.setName("小户");
        userList.add(use4);
        
        for (Use u : userList) {
            System.out.println("name:"+u.getName()+",number:"+u.getNumber());
        }
    }
}

打印无排序list内容

name:小王,number:10
name:小李,number:3
name:小六,number:6
name:小哎,number:2
name:小户,number:11

有排序list方法

package com.rpmc.demo;

import com.crscd.pcap4j.modle.ReturnContactSubModle;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Test {

    public static void main(String[] args) {


        List<Use> userList = new ArrayList<>();
        Use use = new Use();
        use.setNumber(10);
        use.setName("小王");
        userList.add(use);

        Use use1 = new Use();
        use1.setNumber(3);
        use1.setName("小李");
        userList.add(use1);

        Use use2 = new Use();
        use2.setNumber(6);
        use2.setName("小六");
        userList.add(use2);


        Use use3 = new Use();
        use3.setNumber(2);
        use3.setName("小哎");
        userList.add(use3);

        Use use4 = new Use();
        use4.setNumber(11);
        use4.setName("小户");
        userList.add(use4);
        
        userList.sort(Comparator.comparing(Use::getNumber));
        
        for (Use u : userList) {
            System.out.println("name:"+u.getName()+",number:"+u.getNumber());
        }
    }
}

打印有排序list内容

name:小哎,number:2
name:小李,number:3
name:小六,number:6
name:小王,number:10
name:小户,number:11
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页