commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Rich Dougherty <r...@rd.gen.nz>
Subject Re: [collections] Enhancemen Request
Date Wed, 21 May 2003 21:08:48 GMT
Konstantin Priblouda wrote:
> Hi all, 
> 
> I need to create map from collection, objects are
> beans, 
> and key shall be value of certain property. 
> 
> like:
> Map  getCollectionMap(Collection col, String
> propertyName )
> 
> 
> There is getCardinalityMap() which does something
> similar. 
> 
> Or is there already a better alternative?

Hi Konstantin

I don't think any such method exists in [collections]. However, here's 
some code that could suit your needs. It uses PropertyUtils from 
[beanutils]. It seems a bit specialised for [collections], but if anyone 
feels it is useful then they're welcome to add it. :-)

Rich

---

public interface MapEntryGetter {

   public Object getKey(Object object);

   public Object getValue(Object object);

}

public class PropertyKeyMapEntryGetter {

   private String propertyName;

   public PropertyKeyedMapEntryGetter(String propertyName) {
     this.propertyName = propertyName;
   }

   public Object getKey(Object object) {
      PropertyUtils.getProperty(object, propertyName);
   }

   public Object getValue(Object object) {
     return object;
   }

}

public class SomeClass {

   public static putFromCollection(
       Map map,
       Collection collection,
       MapEntryGetter mapEntryGetter) {

     for (Iterator itr = collection.iterator();
          itr.hasNext();;) {
       Object element = itr.next();
       Object key = mapEntryGetter.getKey(element);
       Object value = mapEntryGetter.getValue(element);
       map.put(key, value);
     }
   }

}

Then call like:

mapEntryGetter = new PropertyKeyMapEntryGetter("propertyName");
SomeClass.putFromCollection(map, collection, mapEntryGetter);

Mime
View raw message