Phantomazi
Phantomazi

Reputation: 408

Struggling with the use of a Comparator

The case: I have an ArrayList of objects, which has the following print method:

public void printAllItems()
{
    if(itemsList.isEmpty())
    {
        System.out.println("The list is empty");
    }
    else
    {
        System.out.println("Number of items: " + itemCount);
        for(ShopItem shopItem : itemsList) 
        {
            shopItem.printDetails();
            System.out.println();   // empty line between posts
        }
    }
}

Now I want to sort those objects Alphabetically by one of their fields(itemName and of course its suitable getItemName() method). I went through the Java doc and found that I should use Comparator. The thing is that I didn't actually understood how to implement the Comparator code into the for-loop. Any suggestions ?

P.S. I am sorry, if the question looks awfully easy, but I am still a beginner and I get confused easily :(

Upvotes: 0

Views: 76

Answers (3)

Mister Smith
Mister Smith

Reputation: 28168

You need to create a class implementing Comparator (or an anonymous class). You have it well explained in the Comparator.compare docs.

That is the approach described in the accepted answer.

I'd still like to post the Java 8 approach:

    itemsList
    .stream()
    .sorted(Comparator.comparing(ShopItem::getItemName))
    .forEach(item -> {
        item.printDetails();
        System.out.println();
    });

Upvotes: 0

elias
elias

Reputation: 15490

Considering getItemName() returns a String, add this before the loop:

Collections.sort(itemsList, new Comparator<ShopItem>(){
                     public int compare(ShopItem i1, ShopItem i2){
                         if(i1 == null || i2 == null)
                              return 0; //do properly nullable handling
                         return i1.getItemName().compareTo(i2.getItemName());
                     }
                  });

Upvotes: 2

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

Before printing the collection, you can do:

Collections.sort(itemsList, new Comparator<ShopItem>() {
    public int compare(ShopItem i1, ShopItem i2) {
        return i1.getItemName().compareTo(i2.getItemName());
    }
});

Here I'm using an anonymous implementation of the Comparator interface.

Upvotes: 1

Related Questions