2012-02-06 24 views
0

我有Java bean類,我想通過一個String類型的bean屬性對這些bean的列表進行排序。我怎樣才能做到這一點?如何通過Java中的對象的字符串值進行排序

+2

的可能重複:http://stackoverflow.com/questions/3342517/sorting-arraylist-of-objects-by-object-attribute – Kris 2012-02-06 12:07:10

回答

4

要麼使類型本身實現Comparable<Foo>,通過比較兩個字符串實現compareTo方法,或者實現一個Comparator<Foo>,它再次通過字符串進行比較。

通過第一種方法,您可以直接使用Collections.sort();與第二,你會使用Collections.sort(collection, new FooComparator());

例如:

public class Foo { 
    public String getBar() { 
     ... 
    } 
} 

public class FooComparatorByBar implements Comparator<Foo> { 
    public int compare(Foo x, Foo y) { 
     // TODO: Handle null values of x, y, x.getBar() and y.getBar(), 
     // and consider non-ordinal orderings. 
     return x.getBar().compareTo(y.getBar()); 
    } 
} 
+1

應該就是比較器而不是比較器? – 2012-02-06 12:09:22

+0

@Scobal:是的,正在修復一個更大的編輯。 – 2012-02-06 12:10:47

1

通過使用自定義比較?

import java.util.*; 

class Bean { 
    public final String name; 
    public final int value; 

    public Bean(final String name, final int value) { 
     this.name = name; 
     this.value = value; 
    } 

    @Override 
    public String toString() { 
     return name + " = " + value; 
    } 
} 

public class SortByProp { 
    private static List<Bean> initBeans() { 
     return new ArrayList<Bean>(Arrays.asList(
      new Bean("C", 1), 
      new Bean("B", 2), 
      new Bean("A", 3) 
     )); 
    } 

    private static void sortBeans(List<Bean> beans) { 
     Collections.sort(beans, new Comparator<Bean>() { 
      public int compare(Bean lhs, Bean rhs){ 
       return lhs.name.compareTo(rhs.name); 
      } 
     }); 
    } 


    public static void main(String[] args) { 
     List<Bean> beans = initBeans(); 
     sortBeans(beans); 
     System.out.println(beans); 
    } 
} 
0

使用Guava,它只是

Collections.sort(list, Ordering.natural().compose(Functions.toStringFunction())); 
相關問題