You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@commons.apache.org by Konstantin Priblouda <kp...@yahoo.com> on 2003/05/21 12:29:59 UTC

[collections] Enhancemen Request

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?

regards,

=====
Konstantin Priblouda ( ko5tik )    Freelance Software developer
< http://www.pribluda.de > < play java games -> http://www.yook.de >
< render charts online -> http://www.pribluda.de/povray/ >

__________________________________
Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo.
http://search.yahoo.com

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


Re: [collections] Enhancemen Request

Posted by Rich Dougherty <ri...@rd.gen.nz>.
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);