Java – how to perform a series of sorting operations (multiple sorting conditions) on ArrayList
•
Java
I have an ArrayList of objects on which I want to run a series of sorting operations I want to sort them by name first, and if they are the same, by ID, for example
How can I achieve it?
This is my code
Comparator<Ticket> mc; mc = new TicketIdComparator(); Collections.sort(tickets,mc); final class TicketIdComparator implements Comparator<Ticket> { @Override public int compare(Ticket ticket1,Ticket ticket2) { String TicketId1 = ((Ticket) ticket1).getNumber(); String TickedId2 = ((Ticket) ticket2).getNumber(); int num1=Integer.parseInt(TicketId1); int num2 =Integer.parseInt(TickedId2); if (num1<num2) return 1; if (num1>num2) return -1; return 0; } }
This code sorts the list by ID, but I want to sort the names again
Solution
Collections.sort(myList,new Comparator() {
Collections.sort(myList,new Comparator() { @Override public int compare(Object o1,Object o2) { // write your ordering code here return 0; } });
Just fill in the comparison code you want, and Java will handle sorting for you
Edit updated questions:
Comparator<Ticket> mc; mc = new TicketIdComparator(); Collections.sort(tickets,Ticket ticket2) { String TicketId1 = ((Ticket) ticket1).getNumber(); String TickedId2 = ((Ticket) ticket2).getNumber(); int num1=Integer.parseInt(TicketId1); int num2 =Integer.parseInt(TickedId2); if (num1<num2) return 1; else if (num1>num2) return -1; else return ticket1.getName().compare(ticket2.getName()); } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码