Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are a couple of awkward things with your example class:</p> <ul> <li>it's called People while it has a <code>price</code> and <code>info</code> (more something for objects, not people);</li> <li>when naming a class as a plural of something, it suggests it is an abstraction of more than one thing. </li> </ul> <p>Anyway, here's a demo of how to use a <code>Comparator&lt;T&gt;</code>:</p> <pre><code>public class ComparatorDemo { public static void main(String[] args) { List&lt;Person&gt; people = Arrays.asList( new Person("Joe", 24), new Person("Pete", 18), new Person("Chris", 21) ); Collections.sort(people, new LexicographicComparator()); System.out.println(people); Collections.sort(people, new AgeComparator()); System.out.println(people); } } class LexicographicComparator implements Comparator&lt;Person&gt; { @Override public int compare(Person a, Person b) { return a.name.compareToIgnoreCase(b.name); } } class AgeComparator implements Comparator&lt;Person&gt; { @Override public int compare(Person a, Person b) { return a.age &lt; b.age ? -1 : a.age == b.age ? 0 : 1; } } class Person { String name; int age; Person(String n, int a) { name = n; age = a; } @Override public String toString() { return String.format("{name=%s, age=%d}", name, age); } } </code></pre> <h2>EDIT</h2> <p>And an equivalent Java 8 demo would look like this:</p> <pre><code>public class ComparatorDemo { public static void main(String[] args) { List&lt;Person&gt; people = Arrays.asList( new Person("Joe", 24), new Person("Pete", 18), new Person("Chris", 21) ); Collections.sort(people, (a, b) -&gt; a.name.compareToIgnoreCase(b.name)); System.out.println(people); Collections.sort(people, (a, b) -&gt; a.age &lt; b.age ? -1 : a.age == b.age ? 0 : 1); System.out.println(people); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload