commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Chintan <chin...@mindview.net>
Subject Re: [Collection] Is there a way to branch (group) a collection?
Date Sun, 10 Nov 2002 22:03:04 GMT
I am not aware of any direct functionality but Collection.retainAll() can be used to the grouping.

public interface Predicate {
  public boolean evaluate(Object obj);
}

class Man {
  private int age;
  private String name;
  private Predicate predicate; //Strategy.

  public Man(int a, String n){
    this.age = a;
    this.name = n;
  }

  //override equals
  public boolean equals(Object obj) {
    if(predicate != null)
      return predicate.evaluate(obj);
    else 
      //Override equals here.
      //Do normal comparison 
  }
  public static Collection grouped(Collection sourceCollection, 
      Predicate p, Man type) {
    predicate = p;
    return sourceCollection.retainAll(new ArrayList().add(type));
  }
}

public class FindPredicate{
  public static void main(String[] args){
    ArrayList men = new ArrayList();
    for(int i = 0 ;i < 30; i++)
      men.add(new Man("Name: " + 1, i);
    //From the above collection get all men with age 25
    System.out.println(Man.grouped(men, new Predicate() {
      public boolean evaluate(Object obj) {
        //Compare ages.
        if(age == (Man)obj.age) return true;
        return false;
      }
    }, new Man("", 25));
  }
}



Roman Rytov wrote:

>Assume a collection of objects exists and there is an object
>implementing Predicate interface. Also let's say that evaluate(Object
>obj) method returns a number of distinct objects (out of this
>collection) and the number is noticeably less than total amount of
>objects in the collection. Is there a way to get all collections grouped
>by the predicator? An example may be schematically written like:
> 
>class Man {
>String name;
>int age;
>}
> 
>class AgePredicator implements Predicate {
>    int age;
>    boolean evaluate (Object obj) {
>Man man = (Man)obj;
>return man.age == this.age;
>}
> 
> 
>collection men = { ('Isac', 35), ('Jerry', 32), ('Gonsales', 35),
>('Moshe' , 22), ('Hans', 32), ('Mussa', 32)}
> 
>afer grouping it's supposed to get 3 collections:
> 
>('Isac', 35), ('Gonsales', 35), 
>('Jerry', 32), ('Hans', 32), ('Mussa', 32)}
>('Moshe' , 22), 
> 
> 
>Do we have something in the API do achieve it easily?
> 
> 
>_______________________
>Roman Rytov
>
>
>  
>


--
To unsubscribe, e-mail:   <mailto:commons-dev-unsubscribe@jakarta.apache.org>
For additional commands, e-mail: <mailto:commons-dev-help@jakarta.apache.org>


Mime
View raw message