How to sort an ArrayList in Java

JavaSortingCollectionsArraylist

Java Problem Overview


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??

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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

Solution 3 - Java

Try BeanComparator from Apache Commons.

import org.apache.commons.beanutils.BeanComparator;


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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionranjithView Question on Stackoverflow
Solution 1 - JavaPrabhakaran RamaswamyView Answer on Stackoverflow
Solution 2 - JavabNdView Answer on Stackoverflow
Solution 3 - JavanewuserView Answer on Stackoverflow