Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can declare a priorities hash map:</p> <pre><code>private static final HashMap&lt;String,Integer&gt; PRIORITIES = new HashMap&lt;String, Integer&gt;(); static{ PRIORITIES.put("A", 1); PRIORITIES.put("B", 1); PRIORITIES.put("C", 1); PRIORITIES.put("D", 1); PRIORITIES.put("E", 2); PRIORITIES.put("F", 2); PRIORITIES.put("G", 3); } </code></pre> <p>Then implement <code>compare</code> method of your <code>Comparator</code>:</p> <pre><code>private int getPriority(CustomClass obj) { if(obj!=null&amp;&amp;PRIORITIES.containsKey(obj.getType())) { priority1 = PRIORITIES.get(obj.getType()); } else { priority1 = Integer.MAX_VALUE; } } @Override public int compare(CustomClass o1, CustomClass o2) { int priority1,priority2; priority1 = getPriority(o1); priority2 = getPriority(o2); return priority1==priority2 ? 0 : (priority1&lt;priority2 ? -1 : 1); } </code></pre> <p><strong>UPDATE:</strong> Cleaner approach is to define hashmap in your base class (where <code>getType</code> is declared) and to implement <code>getPriority</code> method: </p> <pre><code>public int getPriority() { return PRIORITIES.containsKey(getType()) ? PRIORITIES.get(getType()) : Integer.MAX_VALUE; } </code></pre> <p>Then <code>Comparator</code> is obvious: </p> <pre><code>@Override public int compare(CustomClass o1, CustomClass o2) { int priority1,priority2; priority1 = o1==null ? Integer.MAX_VALUE : o1.getPriority(); priority2 = o2==null ? Integer.MAX_VALUE : o2.getPriority(); return priority1==priority2 ? 0 : (priority1&lt;priority2 ? -1 : 1); } </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. 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