Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

java - Compare string with comparator method wrt lamda

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;
    }
}

How can I sort the ArrayList with ename? I am able to do with eno which is integer, but for String it's not working for me.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use Comparator.comparing to compare based on a specific field.

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

If you create a getter method for the ename, this can be more elegantly written as:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...