Mahesh
Mahesh

Reputation: 253

How to sort list which having variable as list

I have class ABC

class ABC{
 private List<XYZ> xyzList -- Though its list it contains single object;
 private String txt;
}
class XYZ{
 private long price;
}

I want to sort List abcList based on class XYZ price variable. Please provide best possible approach for sorting in ascending order.

Upvotes: 2

Views: 858

Answers (6)

Java2novice
Java2novice

Reputation: 31

Sample code from http://java2novice.com/java-collections-and-util/arraylist/sort-comparator/

public class MyArrayListSort {

public static void main(String a[]){

    List<Empl> list = new ArrayList<Empl>();
    list.add(new Empl("Ram",3000));
    list.add(new Empl("John",6000));
    list.add(new Empl("Crish",2000));
    list.add(new Empl("Tom",2400));
    Collections.sort(list,new MySalaryComp());
    System.out.println("Sorted list entries: ");
    for(Empl e:list){
        System.out.println(e);
    }
}
}

class MySalaryComp implements Comparator<Empl>{

@Override
public int compare(Empl e1, Empl e2) {
    if(e1.getSalary() < e2.getSalary()){
        return 1;
    } else {
        return -1;
    }
}
}

class Empl{

private String name;
private int salary;

public Empl(String n, int s){
    this.name = n;
    this.salary = s;
}

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public int getSalary() {
    return salary;
}
public void setSalary(int salary) {
    this.salary = salary;
}
public String toString(){
    return "Name: "+this.name+"-- Salary: "+this.salary;
}
}

Upvotes: 0

amicngh
amicngh

Reputation: 7899

One way is implement Comparable interface in XYZ and override compareTo and then Collections.sort(yourListOfXYZ) will sort the list.

Other way is using Comparator.

Collections.sort(xyzList, new Comparator<XYZ>() {
            @Override
            public int compare( XYZ e1,XYZ e2) {
                return Long.valueOf(e1.getPrice()).compareTo(Long.valueOf(e2.getPrice()));
            }
        });

Upvotes: 4

Peter Lawrey
Peter Lawrey

Reputation: 533530

In you case you either need to make XYZ implement Comparable, provide a Comparator<XYZ> or a simpler option is to unwrap it and just use a List<Double> or a SortedSet<Double> to hold you prices.

Upvotes: 0

dvberkel
dvberkel

Reputation: 663

I would suggest you look into the documentation for the Comparable interface. Possible even with the use of an PriorityQueue.

Upvotes: 0

M Abbas
M Abbas

Reputation: 6479

Have you tried one of these methods:

java.util.Collections.sort(List<T>)

Or

java.util.Collections.sort(List<T>, Comparator<? super T>)

Upvotes: 6

gmustudent
gmustudent

Reputation: 2209

Try this

Collections.sort(xyzList);

Upvotes: 1

Related Questions