Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
5 views
in Java by (10.2k points)

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

1 Answer

0 votes
by (46k points)

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

        }

    });

Promptly your fruits list is classified based on fruitName.

Related questions

0 votes
1 answer
asked Aug 6, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
asked Nov 13, 2019 in Java by Nigam (4k points)
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...