0

I have this class:

public class Job {
    private int priority;
    private String name;

    public int getPriority() { 
        return priority; 
    }

    public void setPriority(int priority) { 
        this.priority = priority; 
    }

    public String getName() {
        return name; 
    }

    public void setName(Stirng name) { 
        this.name= name; 
    }
}

and I created some collection of it in the below variable:

List<Job> _jobs = ...

How can I sort the list by priority? (top of the list would be the highest priority value)

I found some reference in the internet but could not find a similar example.

yonan2236
  • 13,371
  • 33
  • 95
  • 141
  • 3
    Errr ... how long did you search? At least on my end, "java sort list property" gives that existing question right there as first link ;-) – GhostCat May 18 '17 at 12:58

2 Answers2

2

Shortes way would be to use the sort method on the list itself, but this requires a mutable list:

list.sort(Comparator.comparingInt(Job::getPriority))

In case you have an immutable list, you may use streams for that:

List<Job> sortedList = list.stream().sorted(Comparator.comparingInt(Job::getPriority)).collect(toList());

In case you're running on a JDK pre 1.8 use the sort method of the Collections class (requires a mutable list):

 Collections.sort(list, new Comparator<Job>() {

        @Override
        public int compare(final Job o1, final Job o2) {

            return o1.getPriority()-o2.getPriority();
        }
    });
Gerald Mücke
  • 10,724
  • 2
  • 50
  • 67
0

You can use a lambda:

    _jobs.sort((a,b) -> Integer.compare(a.getPriority(), b.getPriority()));
    System.out.println(_jobs);
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97