diff --git a/core-java-modules/core-java-collections-maps-6/src/test/java/com/baeldung/strringtomap/StringToMapUnitTest.java b/core-java-modules/core-java-collections-maps-6/src/test/java/com/baeldung/strringtomap/StringToMapUnitTest.java new file mode 100644 index 0000000000..bab4d7dfa7 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-6/src/test/java/com/baeldung/strringtomap/StringToMapUnitTest.java @@ -0,0 +1,89 @@ +package com.baeldung.stringtomap; + +import org.junit.Test; + +import java.util.*; + +import static org.junit.Assert.assertEquals; + +public class StringToMapUnitTest { + + public Map convertStringToMap(String data) { + Map map = new HashMap<>(); + StringTokenizer tokenizer = new StringTokenizer(data, " "); + + while (tokenizer.hasMoreTokens()) { + String token = tokenizer.nextToken(); + String[] keyValue = token.split("="); + map.put(keyValue[0], keyValue[1]); + } + + return map; + } + + @Test + public void given_StringWithKeyValuePairs_whenUsing_convertStringToMap_thenMapCreated() { + String data = "name=John age=30 city=NewYork"; + Map expectedMap = new HashMap<>(); + expectedMap.put("name", "John"); + expectedMap.put("age", "30"); + expectedMap.put("city", "NewYork"); + Map resultMap = convertStringToMap(data); + assertEquals(expectedMap, resultMap); + } + + public Map convertStringArrayToMap(String[] data) { + Map map = new HashMap<>(); + + for (String keyValue : data) { + String[] parts = keyValue.split("="); + map.put(parts[0], parts[1]); + } + + return map; + } + + @Test + public void given_StringArrayWithKeyValuePairs_whenUsing_convertStringArrayToMap_thenMapCreated() { + String[] data = {"name=John", "age=30", "city=NewYork"}; + Map expectedMap = new HashMap<>(); + expectedMap.put("name", "John"); + expectedMap.put("age", "30"); + expectedMap.put("city", "NewYork"); + Map resultMap = convertStringArrayToMap(data); + assertEquals(expectedMap, resultMap); + } + + public Map> convertStringArrayToMapWithDuplicates(String[] data) { + Map> map = new HashMap<>(); + + for (String keyValue : data) { + String[] parts = keyValue.split("="); + String key = parts[0]; + String value = parts[1]; + + if (map.containsKey(key)) { + List valuesList = map.get(key); + valuesList.add(value); + } else { + List valuesList = new ArrayList<>(); + valuesList.add(value); + map.put(key, valuesList); + } + } + + return map; + + } + + @Test + public void given_StringArrayWithKeyValuePairsWithDuplicates_whenUsing_convertStringArrayToMapWithDuplicates_thenMapCreatedWithLists() { + String[] data = {"name=John", "age=30", "city=NewYork", "age=31"}; + Map> expectedMap = new HashMap<>(); + expectedMap.put("name", Collections.singletonList("John")); + expectedMap.put("age", Arrays.asList("30", "31")); + expectedMap.put("city", Collections.singletonList("NewYork")); + Map> resultMap = convertStringArrayToMapWithDuplicates(data); + assertEquals(expectedMap, resultMap); + } +}