1

I have an arrayList of strings, for example:

ArrayList<String> result = new ArrayList<String>() ;
result.add("Name.A");
result.add("Name.B");
result.add("Name.C");
result.add("Type.D");
result.add("Type.E");
result.add("Type.F");

Now I need to convert it into HashMap with one key(before dot) to multiple values(after dot). Like this: Map<String,String[]> map = new HashMap<>(); map(Name= A,B,C) map(Type= D,E,F) Don't know how to do it. Any help would be appreciated


Response response
        = given().
                relaxedHTTPSValidation().
                accept(ContentType.JSON).
                when().
                urlEncodingEnabled(true).
                get(uri).
                then().
                extract().response();
List<String> actual = response.jsonPath().getList("RESPONSE.A_VALUE");

Map<String, String[]> map = new HashMap<>();


        for (String pair : actual) //iterate over the pairs
        {
            if (pair.contains(".")) {
                String[] pair_values = pair.split("\\.");
                map.put(pair_values[0].trim(), pair_values[1].trim());
            }
        }
rdhd
  • 85
  • 1
  • 1
  • 9
  • 2
    What have you tried so far? This is not a code writing service, please provide your code and show where it fails. – gonutz Oct 24 '17 at 13:31
  • Um, since you already mentioned the verb in the question, could you look at String.split method? – Vlasec Oct 24 '17 at 13:34

2 Answers2

1

Using Java 8 streams

ArrayList<String> result = new ArrayList<String>() ;
result.add("Name.A");
result.add("Name.B");
result.add("Name.C");
result.add("Type.D");
result.add("Type.E");
result.add("Type.F");

Map<String, List<String>> returnValue = result.stream()
    .map(p -> p.split("\\.", 2))
    .filter(p -> p.length == 2)
    .collect(
        Collectors.groupingBy(
            p -> p[0],
            Collectors.mapping(
                p -> p[1],
                Collectors.toList())));

System.out.println(returnValue);

This splits the values by dot into at most 2 groups, and then groups the values by their first part.

jrtapsell
  • 6,719
  • 1
  • 26
  • 49
0

I would like to use List<String> because you don't know the length of the array (value of Map) like this :

Map<String, List<String>> map = new HashMap<>();
for (String str : result) {
    String[] spl = str.split("\\.");//Split each string with dot(.)
    if (!map.containsKey(spl[0])) {//If the map not contains this key (left part)
        map.put(spl[0], new ArrayList<>(Arrays.asList(spl[1])));//then add a new node
    } else {
        map.get(spl[0]).add(spl[1]);//else add to the list the right part
    }
}

Outputs

{Type=[D, E, F], Name=[A, B, C]}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • 1
    Thank you. My mistake was that I didn't know how to do check if containsKey() and at one case add string, at another list. – rdhd Oct 24 '17 at 13:49