开发者

Java convert {String,String}[] to Map<String,String[]>

Given the class:

 public class CategoryValuePair
 {
      String category;
      String value;
 }

And a method:

public Map<String,List<String>> convert(CategoryValuePair[] values);

Given that in values we c开发者_如何学Goan receive many entries with the same category, I want to convert these into a Map grouped on category.

Is there a quick / efficient way to perform this conversion?


As far as I know there is not easier way than iterating on values, and then putting the values in the map (like some predefined method).

Map<String, List<String>> map = new HashMap<String, List<String>>();
if (values != null) {
    for (CategoryValuePair cvp : values) {
      List<String> vals = map.get(cvp.category);
      if (vals == null) {
        vals = new ArrayList<String>();
        map.put(cvp.category, vals);
      }
      vals.add(cvp.value);
    }
}

I changed the map values from String[] to List<String> since it seems easier to me to use that so you don't have to hassle with array resizing.


To make it in fewer lines of code, use Google Collections:

public Map<String, Collection<String>> convert(CategoryValuePair[] values) {
    Multimap<String, String> mmap = ArrayListMultimap.create();
    for (CategoryValuePair value : values) {
        mmap.put(value.category, value.value);
    }
    return mmap.asMap();
}

If you don't want to allow duplicate values, replace ArrayListMultimap with HashMultimap.


With lambdaj you just need one line of code to achieve that result as it follows:

group(values, by(on(CategoryValuePair.class).getCategory()));


Just for the sake of implementation... The method returns Map and also checks for duplicates in the arrays... though performance wise its heavy ...

public Map<String,String[]> convert(CategoryValuePair[] values)
{
    Map<String, String[]> map = new HashMap<String, String[]>();
    for (int i = 0; i < values.length; i++) {
        if(map.containsKey(values[i].category)){
            Set<String> set = new HashSet<String>(Arrays.asList(map.get(values[i].category)));
            set.add(values[i].value);
            map.put(values[i].category, set.toArray(new String[set.size()]));
        }else {
            map.put(values[i].category, new String[]{values[i].value});
        }
    }

    return map;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜