Note that there are some explanatory texts on larger screens.

plurals
  1. POBest way to filter out collections based on certain rules
    primarykey
    data
    text
    <p>I am trying to find a best way to filter out some items from a list based on certain rules. For example we have</p> <pre><code>public class Person{ String name; String sex; String dob; String contactNo; Person(String name, String sex, String dob, String contactNo) { this.name = name; this.sex = sex; this.dob = dob; this.contactNo = contactNo; } } List&lt;Person&gt; persons = Arrays.asList(new Person("Bob", "male", "19800101", "12345"), new Person("John", "male", "19810101", "12345"), new Person("Tom", "male", "19820101", "12345"), new Person("Helen", "female", "19800101", "12345"), new Person("Jack", "male", "19830101", "12345"), new Person("Suan", "female", "19850101", "12345")); </code></pre> <p>I want to remove the pair of male and female which have the same dob and contactNo (Remove Bob and Helen in above example). I implemented this as below using a nested loop which worked but looks ugly. Is there a better to achieve this please? Can I implement predicate to do this? </p> <pre><code>public void filterPersons() { List&lt;Person&gt; filtered = new ArrayList&lt;Person&gt;(); for (Person p: persons) { boolean pairFound = false; for (Person t: persons) { if ((p.sex.equals("male") &amp;&amp; t.sex.equals("female")) || (p.sex.equals("female") &amp;&amp; t.sex.equals("male"))) { if (p.dob.equals(t.dob) &amp;&amp; p.contactNo.equals(t.contactNo)) { pairFound = true; break; } } } if (!pairFound) {filtered.add(p);} } System.out.println("filtered size is: " + filtered.size()); for (Person p: filtered) { System.out.println(p.name); } } </code></pre> <p>Many thanks.</p> <p>I've rewritten the above method something like below which looks better imho:</p> <pre><code>public void testFilter() { Predicate&lt;Person&gt; isPairFound = new Predicate&lt;Person&gt;() { @Override public boolean apply(Person p) { boolean pairFound = false; for (Person t: persons) { if ((p.sex.equals("male") &amp;&amp; t.sex.equals("female")) || (p.sex.equals("female") &amp;&amp; t.sex.equals("male"))) { if (p.dob.equals(t.dob) &amp;&amp; p.contactNo.equals(t.contactNo)) { pairFound = true; break; } } } return pairFound; } }; Iterable&lt;Person&gt; filtered = Iterables.filter(persons, isPairFound); for (Person p: filtered) { System.out.println(p.name); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    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.
 

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