私はクラスABCを持っています
class ABC{
private List<XYZ> xyzList -- Though its list it contains single object;
private String txt;
}
class XYZ{
private long price;
}
クラスXYZ価格変数に基づいてリストabcListをソートしたいと思います。昇順で並べ替えるための最善のアプローチを提供してください。
私はクラスABCを持っています
class ABC{
private List<XYZ> xyzList -- Though its list it contains single object;
private String txt;
}
class XYZ{
private long price;
}
クラスXYZ価格変数に基づいてリストabcListをソートしたいと思います。昇順で並べ替えるための最善のアプローチを提供してください。
次のいずれかの方法を試しましたか。
java.util.Collections.sort(List<T>)
または
java.util.Collections.sort(List<T>, Comparator<? super T>)
Comparable
1 つの方法は、インターフェイスを実装しXYZ
てオーバーライドcompareTo
しCollections.sort(yourListOfXYZ)
、リストを並べ替えることです。
他の方法は、を使用して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()));
}
});
これを試して
Collections.sort(xyzList);
Comparableインターフェースのドキュメントを調べることをお勧めします。PriorityQueueを使用しても可能です。
XYZ を実装する必要がある場合は、 aまたはより簡単なオプションをComparable
提供する必要があります。Comparator<XYZ>
List<Double>
SortedSet<Double>
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;
}
}