Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: how to convert a List<?> to a Map<String,?> [duplicate]

I would like to find a way to take the object specific routine below and abstract it into a method that you can pass a class, list, and fieldname to get back a Map. If I could get a general pointer on the pattern used or , etc that could get me started in the right direction.

  Map<String,Role> mapped_roles = new HashMap<String,Role>();
    List<Role> p_roles = (List<Role>) c.list();
    for (Role el :  p_roles) {
        mapped_roles.put(el.getName(), el);
    }

to this? (Pseudo code)

  Map<String,?> MapMe(Class clz, Collection list, String methodName)
  Map<String,?> map = new HashMap<String,?>();
    for (clz el :  list) {
        map.put(el.methodName(), el);
    }

is it possible?

like image 697
ebt Avatar asked Jul 07 '10 23:07

ebt


1 Answers

Using Guava (formerly Google Collections):

Map<String,Role> mappedRoles = Maps.uniqueIndex(yourList, Functions.toStringFunction());

Or, if you want to supply your own method that makes a String out of the object:

Map<String,Role> mappedRoles = Maps.uniqueIndex(yourList, new Function<Role,String>() {
  public String apply(Role from) {
    return from.getName(); // or something else
  }});
like image 58
Jorn Avatar answered Sep 20 '22 15:09

Jorn