使用comparator方法wrt lamda比较字符串

wgx48brx  于 2021-06-26  发布在  Java
关注(0)|答案(2)|浏览(396)
import java.util.ArrayList;
import java.util.Collections;

public class OwnCustomizeLamdaExample {

    public static void main(String[] args) {

        Employe e1 = new Employe(100, "Saket");

        System.out.println("E1 object value is " +e1);

        ArrayList<Employe> al = new ArrayList<>();
        al.add(new Employe(200, "Sammi"));
        al.add(new Employe(600, "Raj"));
        al.add(new Employe(300, "Mallika"));
        al.add(new Employe(800, "Hari"));
        al.add(new Employe(1100, "Sunny"));
        al.add(new Employe(2200, "Bunny"));

        System.out.println("Value of al is " + al);

        Collections.sort(al, (l1,l2)-> (l1.eno>l2.eno)?-1:(l1.eno<l2.eno)?1:0);
        System.out.println("Value of al after sort eno " + al);

      **Collections.sort(al, (l1,l2)-> (l1.ename.equals(l2.ename))?-1:(l1.ename.equals(l2.ename)?1:0));
        System.out.println("Value of al after sort  ename" + al);**
    }
}

class Employe{

    int eno;
    String ename;

    Employe(int eno,String ename){
        this.eno=eno;
        this.ename=ename;
    }

    @Override
    public String toString() {

        return eno + ":" + ename;
    }
}

我该如何分类 ArrayListename ? 我可以用eno做整数,但是对于字符串它不适合我。

zpjtge22

zpjtge221#

使用比较器。对于自然语言(特定语言环境),请使用 Collator.getInstance 它也是一个比较器,用于排序ĉ定义ĝ小时ĥ...

Collections.sort(al, Comparator.comparing(l -> l.eno).reversed());
    Collections.sort(al, Comparator.comparing(l -> l.ename));
    Collections.sort(al, Comparator.comparing(l -> l.ename,
            Collator.getInstance(Locale.FRANCE)));

合并:

Collections.sort(al, Comparator.comparing(l -> l.eno).reversed()
                         .thenComparing(l -> l.ename));
qybjjes1

qybjjes12#

你可以用 Comparator.comparing 根据特定领域进行比较。

Collections.sort(al, Comparator.comparing(e -> e.ename));

如果为 ename ,可以更优雅地写为:

Collections.sort(al, Comparator.comparing(Employe::getEName));

相关问题