[java] How to sort an ArrayList in Java

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.

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

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

how??

This question is related to java sorting collections arraylist

The answer is


Use a Comparator like this:

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.


Try BeanComparator from Apache Commons.

import org.apache.commons.beanutils.BeanComparator;


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

Implement Comparable interface to Fruit.

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

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to sorting

Sort Array of object by object field in Angular 6 Sorting a list with stream.sorted() in Java How to sort dates from Oldest to Newest in Excel? how to sort pandas dataframe from one column Reverse a comparator in Java 8 Find the unique values in a column and then sort them pandas groupby sort within groups pandas groupby sort descending order Efficiently sorting a numpy array in descending order? Swift: Sort array of objects alphabetically

Examples related to collections

Kotlin's List missing "add", "remove", Map missing "put", etc? How to unset (remove) a collection element after fetching it? How can I get a List from some class properties with Java 8 Stream? Java 8 stream map to list of keys sorted by values How to convert String into Hashmap in java How can I turn a List of Lists into a List in Java 8? MongoDB Show all contents from all collections Get nth character of a string in Swift programming language Java 8 Distinct by property Is there a typescript List<> and/or Map<> class/library?

Examples related to arraylist

Adding null values to arraylist How to iterate through an ArrayList of Objects of ArrayList of Objects? Dynamically adding elements to ArrayList in Groovy How to replace existing value of ArrayList element in Java How to remove the last element added into the List? How to append elements at the end of ArrayList in Java? Removing Duplicate Values from ArrayList How to declare an ArrayList with values? In Java, can you modify a List while iterating through it? Load arrayList data into JTable