如何在 Java 中对 ArrayList 进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18441846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:39:12  来源:igfitidea点击:

How to sort an ArrayList in Java

javasortingcollectionsarraylist

提问by ranjith

I have a class named Fruit. I am creating a list of this class and adding each fruit in the list. I want to sort this list based on the order of fruit name.

我有一个名为 Fruit 的类。我正在创建此类的列表并将每个水果添加到列表中。我想根据水果名称的顺序对这个列表进行排序。

public class Fruit{

    private String fruitName;
    private String fruitDesc;
    private int quantity;

    public String getFruitName() {
        return fruitName;
    }
    public void setFruitName(String fruitName) {
        this.fruitName = fruitName;
    }
    public String getFruitDesc() {
        return fruitDesc;
    }
    public void setFruitDesc(String fruitDesc) {
        this.fruitDesc = fruitDesc;
    }
    public int getQuantity() {
        return quantity;
    }
    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }
}

and I am creating its list using for loop

我正在使用 for 循环创建它的列表

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

Fruit fruit;
for(int i=0;i<100;i++)
{
   fruit = new fruit();
   fruit.setname(...);
   fruits.add(fruit);
}

and I need to sort this arrayList using the fruit name of each object in the list

我需要使用列表中每个对象的水果名称对这个 arrayList 进行排序

how??

如何??

采纳答案by Prabhakaran Ramaswamy

Use a Comparatorlike this:

使用Comparator这样的:

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

Fruit fruit;
for(int i = 0; i < 100; i++)
{
  fruit = new Fruit();
  fruit.setname(...);
  fruits.add(fruit);
}

// Sorting
Collections.sort(fruits, new Comparator<Fruit>() {
        @Override
        public int compare(Fruit fruit2, Fruit fruit1)
        {

            return  fruit1.fruitName.compareTo(fruit2.fruitName);
        }
    });

Now your fruits list is sorted based on fruitName.

现在您的水果列表基于fruitName.

回答by bNd

Implement Comparableinterface to Fruit.

实现Fruit 的Comparable接口。

public class Fruit implements Comparable<Fruit> {

It implements the method

它实现了方法

@Override
    public int compareTo(Fruit fruit) {
        //write code here for compare name
    }

Then do call sort method

然后调用排序方法

Collections.sort(fruitList);

回答by newuser

Try BeanComparatorfrom Apache Commons.

试试Apache Commons 的BeanComparator

import org.apache.commons.beanutils.BeanComparator;


BeanComparator fieldComparator = new BeanComparator("fruitName");
Collections.sort(fruits, fieldComparator);