Jak posortować Arraylistę w Javie [duplicate]

To pytanie ma już odpowiedź tutaj:

Mam klasę o nazwie Fruit. Tworzę listę tej klasy i dodaję każdy owoc na liście. Chcę posortować tę listę na podstawie kolejności nazw owoców.
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;
    }
}

I tworzę jego listę używając pętli for

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

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

Oraz Muszę posortować tę arraylistę używając nazwy owocu każdego obiektu na liście

Jak??
Author: dream_world, 2013-08-26

3 answers

Użyj Comparator w ten sposób:

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);
        }
    });

Teraz Twoja lista owoców jest posortowana na podstawie fruitName.

 399
Author: Prabhakaran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-28 09:19:11

Zaimplementujporównywalny interfejs do Fruit.

public class Fruit implements Comparable<Fruit> {

Implementuje metodę

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

Następnie wywołaj metodę sortowania

Collections.sort(fruitList);
 87
Author: bNd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-05 10:33:53

Try BeanComparator

BeanComparator fieldComparator = new BeanComparator(
                "fruitName");
Collections.sort(fruits, fieldComparator);
 12
Author: newuser,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-26 10:27:39