dcsimg
utilities for Maps
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Rami_Abramson
Posted On:   Monday, January 8, 2007 06:26 AM

			
Hello all,

Is there some utility class[s] that allow smart manipulations to maps? (Something parallel to Collections/Arrays classes)

For example, the ability to instatiate a Map from a Collection when the keys are taken by calling a getter function of the objects of the collection, and the values are the object themselves.

thank you,

Rami

Re: utilities for Maps

Posted By:   WarnerJan_Veldhuis  
Posted On:   Monday, January 8, 2007 07:15 AM

Your example isn't that hard too cook up... Using reflection you can query the object quite easily. This example is way off from being fool-proof (null checks for example...), but it gives a general idea. The getter for the fieldname should be written in the Java spec case, so a fieldname town, would have a getter getTown(). Simple as that :)



I had 5 minutes to spare so there you go: (Obviously the main() method, and the TestObject are there for errmmm, well, testing purposes...)


import java.util.*;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;

public class MapUtil {

public static Map generateMap( Collection c, String fieldname) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
Map result = new HashMap();
for (Object o : c) {
Method m = o.getClass().getMethod( "get" + String.valueOf(fieldname.charAt( 0)).toUpperCase() + fieldname.substring( 1) , new Class[0]);
result.put( m.invoke(o,null), o );
}

return result;
}

public static void main( String[] args ) {
List l = new ArrayList( );
l.add( new TestObject( "first") );
l.add( new TestObject( "second") );
l.add( new TestObject( "third") );
l.add( new TestObject( "fourth") );

try {
Map m = generateMap( l, "name");
for ( Iterator i = m.entrySet().iterator(); i.hasNext(); ) {
Map.Entry entry = (Map.Entry) i.next();
System.out.println( "key: " + entry.getKey() + ", value: " + entry.getValue() );
}

}
catch ( NoSuchMethodException e ) {
e.printStackTrace();
}
catch ( IllegalAccessException e ) {
e.printStackTrace();
}
catch ( InvocationTargetException e ) {
e.printStackTrace();
}
}


}
class TestObject {
private String name;

public TestObject( String name ) {
this.name = name;
}

public String getName() {
return name;
}

public String toString() {
final StringBuffer sb = new StringBuffer();
sb.append( "TestObject" );
sb.append( "{name='" ).append( name ).append( '\'' );
sb.append( '}' );
return sb.toString();
}
}

About | Sitemap | Contact