-3

I have this ArrayList called 'sortList'. I'm adding objects to it. The objects are of type 'MailItem'. I want to sort my ArrayList according to the object's (item's) getPriorityLevel(). How can I do that?

Additional information: getPriorityLevel() returns a String.

This is what I've done till now:

package strategies;

import java.util.ArrayList;

import automail.IMailSorter;
import automail.MailItem;
import automail.StorageTube;

public class MailSorter implements IMailSorter{

    MailItem item;

    private ArrayList<MailItem> sortList =new ArrayList<MailItem>();

    public void addToList(MailItem item)
    {
        if (item.getPriorityLevel()=="High")
        {

            MailItem highPriorityItem= new MailItem(item.getDestFloor(), item.getSize(), item.getPriorityLevel(), item.getArrivalTime() );

            sortList.add(highPriorityItem);

        }

        if (item.getPriorityLevel()=="Medium")
        {

            MailItem mediumPriorityItem=new MailItem(item.getDestFloor(), item.getSize(), item.getPriorityLevel(), item.getArrivalTime() );

            sortList.add(mediumPriorityItem);
        }

        if (item.getPriorityLevel()=="Low")
        {
            MailItem lowPriorityItem=new MailItem(item.getDestFloor(), item.getSize(), item.getPriorityLevel(), item.getArrivalTime() );

            sortList.add(lowPriorityItem);
        }


    }

    @Override
    public boolean fillStorageTube(StorageTube tube) {
        // TODO Auto-generated method stub
        return false;
    }}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • 3
    Possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Guy Mar 19 '17 at 07:27
  • *"How can I do that, i.e. sort my ArrayList according to the object's (item's) getPriorityLevel()?"* By calling `sort()` with a custom `Comparator`. – Andreas Mar 19 '17 at 07:28
  • 3
    You're doing the *exact same thing* in the 3 `if` statements in `addToList()`, so what is the point of the `if` statements? – Andreas Mar 19 '17 at 07:30
  • 1
    Don't use an Arraylist at all. Use a PriorityQueue so your objects always remain sorted as you add – OneCricketeer Mar 19 '17 at 07:32
  • 3
    @Guy: No, this question is asking us how to do something that the code above doesn't even try to do. But the `==` with strings is certainly ***a*** problem in the code... – T.J. Crowder Mar 19 '17 at 07:32
  • 4
    Possible duplicate of [Sort ArrayList of custom Objects by property](http://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property) – OneCricketeer Mar 19 '17 at 07:34
  • @Andreas, the if statements prevent other adding other priorities :) – OneCricketeer Mar 19 '17 at 07:35
  • @Shubam Also see this http://stackoverflow.com/questions/683041/how-do-i-use-a-priorityqueue – OneCricketeer Mar 19 '17 at 07:38
  • @cricket_007 LOL :-P I doubt that was the intention. If it had been, using `||` would be better than duplicating code. Keep [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself), you comedian. ;-) – Andreas Mar 19 '17 at 07:39
  • *FYI:* If you want the insertion order of mail items with same priority to be honored, you can't use [`PriorityQueue`](https://docs.oracle.com/javase/8/docs/api/java/util/PriorityQueue.html), since *"If multiple elements are tied for least value, the head is **one of** those elements -- ties are broken **arbitrarily**."*. – Andreas Mar 19 '17 at 07:43

2 Answers2

0

Check Comparator interface in java. It provides ways to sort based on different properties. You can have a comparator for the property on which you want to sort.

http://www.javatpoint.com/Comparator-interface-in-collection-framework

Abhay Jain
  • 86
  • 5
0

Here is a short demonstration of a use of a comperator. Treat it as a very simplified demo, and not a robust production code:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class MailSorter{

    MailItem item;

    private ArrayList<MailItem> sortList =new ArrayList<>();

    void addToList(MailItem item) { sortList.add(item);}

    ArrayList<MailItem> getSortedList(){
        Collections.sort(sortList, new MailComperator() );
        return sortList;
    }

    public class MailComperator implements Comparator<MailItem> {

        @Override
        public int compare(MailItem o1, MailItem o2) {
            return o1.getPriorityLevel().compareTo(o2.getPriorityLevel());
        }
    }

    public static void main(String args[]) {

        MailSorter ms = new MailSorter();

        ms.addToList(new MailItem("Low"));
        ms.addToList(new MailItem("Medium"));
        ms.addToList(new MailItem("Low"));
        ms.addToList(new MailItem("High"));
        ms.addToList(new MailItem("Medium"));
        ms.addToList(new MailItem("Low"));
        ms.addToList(new MailItem("High"));

        ms.getSortedList().stream().forEach(e -> System.out.println(e.getPriorityLevel()));
    }
}

class MailItem {

    private String priorityLevel;

    MailItem(String priorityLevel){
        this.priorityLevel = priorityLevel; //you may want to check ! null
    }

    String getPriorityLevel() { return priorityLevel;}
}

Note the code is a MCVE version of the posted code. I believe this contributes too higher quality questions and answers.

c0der
  • 18,467
  • 6
  • 33
  • 65