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

Given the class:

 public class CategoryValuePair
 {
      String category;
      String value;
 }

And the method:

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

Given that in valueswe can get many records with the same category, I want to convert them into a category Mapgrouped by categories.

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

+3
source share
4 answers

To do this 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 do not want to allow duplicate values, replace ArrayListMultimap with HashMultimap.

+1
source

, , , (, ).

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);
    }
}

String[] List<String>, , .

+2

With lambdaj, you just need one line of code to achieve this result:

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

Just for implementation ... The method returns Map, and also checks for duplicates in arrays ... although its wise performance is 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
source

Source: https://habr.com/ru/post/1751515/


All Articles