Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You could iterate over your collection of elements adding them into a <code>Map</code> associating the key (prefix) to the value (object). Every time an element is added you check if the element stored with the same prefix is bigger than the one being added.</p> <p>In order to have this behavior:</p> <pre><code>provides this: [{a1 5}, {b2 3}, {g1 1}, {b5 1}, {c9 11}, {g2 3}, {d1 4}, {b3 19}] results this: [{a1 5}, {c9 11}, {g2 3}, {d1 4}, {b3 19}] </code></pre> <p>You could implement something like this:</p> <pre><code>import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class TestSystemOut { public static void main(final String[] a) { List&lt;MyObj&gt; list = prepareList(); System.out.println("provides this: " + list); Map&lt;String, MyObj&gt; map = new LinkedHashMap&lt;String, MyObj&gt;(); // if result order doesn't matter this can be a simple HashMap String strTmp; for (MyObj obj : list) { strTmp = obj.str; strTmp = strTmp.substring(0, strTmp.length() - 1); if (map.get(strTmp) == null || map.get(strTmp).integer &lt; obj.integer) { map.remove(strTmp); // this could be removed if order of result doesn't matter map.put(strTmp, obj); } } list.clear(); list.addAll(map.values()); System.out.println("results this: " + list); } public static class MyObj { String str; Integer integer; public MyObj(final String str, final Integer integer) { super(); this.str = str; this.integer = integer; } @Override public String toString() { return "{" + str + " " + integer + "}"; } } private static List&lt;MyObj&gt; prepareList() { List&lt;MyObj&gt; list = new ArrayList&lt;MyObj&gt;(); list.add(new MyObj("a1", 5)); list.add(new MyObj("b2", 3)); list.add(new MyObj("g1", 1)); list.add(new MyObj("b5", 1)); list.add(new MyObj("c9", 11)); list.add(new MyObj("g2", 3)); list.add(new MyObj("d1", 4)); list.add(new MyObj("b3", 19)); return list; } } </code></pre>
 

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