按对象名称对对象列表进行排序

时间:2012-05-14 10:31:25

标签: java

我有一个 Fruit 模型类:

public class Fruit{
   private String name;
   private String color;

   public Fruit(String name, color){
     this.name = name;
     this.color = color;
   }
   public getName(){
      return name;
   }
   public getColor(){
      return color;
   }
}

然后,我创建了一个fruits的列表:

List<Fruit> fruits = new ArrayList<Fruit>();

fruits.add(new Fruit("Orange","orange"));
fruits.add(new Fruit("Strawberry","red"));
fruits.add(new Fruit("Apple","green"));
fruits.add(new Fruit("Banana","yellow"));

现在,我想按水果名称字母顺序中的fruits元素进行排序。我怎样才能有效地对水果清单进行排序?

6 个答案:

答案 0 :(得分:3)

您可以使用Collections.sort(),定义Comparator。例如:

Collections.sort(
    fruits,
    new Comparator<Fruit>()
    {
        public int compare(Fruit f1, Fruit f2)
        {
            // Ignore case for alphabetic ordering.
            return f1.getName().compareToIgnoreCase(f2.getName());
        }
    });

答案 1 :(得分:2)

使用以下

Collections.sort(fruits);

public class Fruit implements Comparable {

    public int compareTo(Object o) {            
        Fruit f = (Fruit) o;
        return this.getName().compareTo(f.getName());
    }

}

答案 2 :(得分:1)

在fruit类上实现comparable接口,并使用Collections.sort(list) http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html

答案 3 :(得分:0)

您可以使用比较器。有关文档,请查看 http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html

答案 4 :(得分:0)

public class Fruit implements Comparable<Fruit> {
{
   public int compareTo(Fruit f) {
       if (this.Name == f.Name)
           return 0;
       else if (this.Name > f.Name)
           return 1;
       else
           return -1;
    }
}

像这样使用:

Collections.sort(fruits);

答案 5 :(得分:0)

public Comparator<Fruit> fruitComparator = new Comparator<Fruit>() {
        @Override
        public int compare(Fruit f1, Fruit f2) {

            return f1.getName().compareTo(f2.getName());
        }
    };

然后:

Collections.sort(fruits, fruitComparator );
相关问题