2012-02-06 2 views

답변

4

형식 자체를 Comparable<Foo>으로 구현하고 두 문자열을 비교하여 compareTo 메서드를 구현하거나 Comparator<Foo>을 구현하여 문자열을 다시 비교하십시오.

첫 번째 방법을 사용하면 Collections.sort()을 직접 사용할 수 있습니다. 사용자 정의 비교기를 사용하여

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

해야 Comparer보다는 Comparator가 좋습니까? –

+0

@Scobal : 예, 더 큰 편집을 수정했습니다. –

1

: 두 번째로는 예를 들어 Collections.sort(collection, new FooComparator());

를 사용하는 거라고? Guava를 사용

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

, 그냥

Collections.sort(list, Ordering.natural().compose(Functions.toStringFunction())); 
관련 문제