-1

I need to convert a String to List<Map<String, String>>> for pass JUnit Test. I have this:

String userAttributes = "[{name=test, cp=458999, lastname=test2}]";

That i want is in the tests (Mockito) change a call to a server with this values, something like this:

Mockito.when(template.search(Mockito.anyString, new AttributesMapper()).thenReturn(attributes);

I need List<Map<String, String>>> for do this:

user.setUserName(attributes.get("name"));
Koray Tugay
  • 22,894
  • 45
  • 188
  • 319
jdflores
  • 407
  • 7
  • 25
  • 1
    Possible duplicate of [How to convert String into Hashmap in java](https://stackoverflow.com/questions/26485964/how-to-convert-string-into-hashmap-in-java) – Nitin Zadage Oct 25 '19 at 10:19
  • Provide an answer instead of editing your question to add a SOLUTION section. – Koray Tugay Oct 25 '19 at 11:41
  • Can you say if given ansvers solve your problem or say what's wrong are with them? Respond on answers helps in future to precise the answers. – lczapski Oct 28 '19 at 16:56

2 Answers2

0

Try regex or split by special char. First remove parentheses from beginning and end. After that you can split it by , and = to collect strings to map.

String userAttributes = "[{name=test, cp=458999, lastname=test2}]";

List<String> strings = Arrays.asList(userAttributes
      .replace("[{","").replace("}]","")
      .split(", "));
Map<String, String> collect = strings.stream()
      .map(s -> s.split("="))
      .collect(Collectors.toMap(s -> s[0], s -> s[1]));

System.out.println(collect.get("name"));

Other approach with Pattern

Map<String, String> collect = Pattern.compile(",")
        .splitAsStream(userAttributes
                .replace("[{","").replace("}]",""))
        .map(s -> s.split("="))
        .collect(Collectors.toMap(s -> s[0], s -> s[1]));

Or if you really wants use List<Map<String, String>>>. But after that you can not do this user.setUserName(attributes.get("name"));

List<Map<String, String>> maps = strings.stream()
      .map(s -> s.split("="))
      .map(s -> Map.of(s[0], s[1]))
      .collect(Collectors.toList());

System.out.println(maps);
lczapski
  • 4,026
  • 3
  • 16
  • 32
-1
    String userAttributes = "[{name=test, cp=458999, lastname=test2}]";
    StringTokenizer stringTokenizer = new StringTokenizer(userAttributes,",");
    List<Map<String,String>> list = new ArrayList<>();
    while(stringTokenizer.hasMoreElements()){
        StringTokenizer stringTokenizer2 = new StringTokenizer((String)stringTokenizer.nextElement(),"=");
        while(stringTokenizer2.hasMoreElements()){
            Map<String, String> map = new HashMap<>();
            map.put( ((String)stringTokenizer2.nextElement()),((String)stringTokenizer2.nextElement()) );
            list.add(map);
        }
    }

    System.err.println(list.toString());