Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Take a look at the <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html" rel="nofollow">java.util.Comprator</a> interface. You can write a method that iterates over a List and uses a comparator to find the one you are after.</p> <p>Something like (not compiled):</p> <pre><code>for(final T value : list) { if(comparator.compare(value, desired) == 0) { // match } } </code></pre> <p>In your comparator you have it perform whatever comparison you want.</p> <p>Here is a working example:</p> <pre><code>public class JavaApplication4 { public static void main(String[] args) { final List&lt;Data&gt; list; final List&lt;Data&gt; a; final List&lt;Data&gt; b; list = new ArrayList&lt;Data&gt;(); list.add(new Data("Foo", 1)); list.add(new Data("Bar", 10)); list.add(new Data("Car", 10)); a = find(list, new Data("Bar", 0), new Comparator&lt;Data&gt;() { @Override public int compare(final Data o1, final Data o2) { return (o1.name.compareTo(o2.name)); } }); b = find(list, new Data(null, 10), new Comparator&lt;Data&gt;() { @Override public int compare(final Data o1, final Data o2) { return (o1.count - o2.count); } }); System.out.println(a.size()); System.out.println(b.size()); } private static List&lt;Data&gt; find(final List&lt;Data&gt; list, final Data desired, final Comparator&lt;Data&gt; comprator) { final List&lt;Data&gt; results; results = new ArrayList(list.size()); for(final Data data : list) { if(comprator.compare(desired, data) == 0) { results.add(data); } } return (results); } private static class Data { private final String name; private final int count; Data(final String nm, final int c) { name = nm; count = c; } } } </code></pre> <p>And here is a generic version of the <code>find</code> method. Using this method you would never have to write the find method again, using a method that embeds the logic for matching in the iteration code means that you would have to re-write the iteration logic for each new set of matching logic.</p> <pre><code>private static &lt;T&gt; List&lt;T&gt; find(final List&lt;T&gt; list, final T desired, final Comparator&lt;T&gt; comprator) { final List&lt;T&gt; results; results = new ArrayList(list.size()); for(final T value : list) { if(comprator.compare(desired, value) == 0) { results.add(value); } } return (results); } </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.
 

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