0

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 :(

Simon McLoughlin
  • 8,293
  • 5
  • 32
  • 56
Phantomazi
  • 408
  • 6
  • 22
  • You wouldn't put the Comparator in the for loop, it would go before it. Also I think you can just do `shopItem.Sort(itemName)` – j.con Apr 03 '14 at 13:12
  • You don't implement it with the `for` loop; you sort the collection first (using [`Collections#sort`](http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort) and then iterate through (using `for` loop). Check out [this question](http://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property), it has lots of examples. – Paul Richter Apr 03 '14 at 13:15

3 Answers3

2

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());
                     }
                  });
elias
  • 15,010
  • 4
  • 40
  • 65
1

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.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
0

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();
    });
Mister Smith
  • 27,417
  • 21
  • 110
  • 193