BAEL-8901 Add section in "Stream operations on Strings" article

- Added string array to map example.
This commit is contained in:
Dhawal Kapil 2018-09-12 12:13:51 +05:30
parent 977c50ad85
commit 708d64c183
2 changed files with 25 additions and 0 deletions

View File

@ -2,6 +2,7 @@ package com.baeldung.string;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@ -32,5 +33,12 @@ public class JoinerSplitter {
.mapToObj(item -> (char) item)
.collect(Collectors.toList());
}
public static Map<String, String> arrayToMap(String[] arrayOfString) {
return Arrays.asList(arrayOfString)
.stream()
.map(str -> str.split(":"))
.collect(Collectors.<String[], String, String>toMap(str -> str[0], str -> str[1]));
}
}

View File

@ -3,7 +3,9 @@ package com.baeldung.string;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
@ -62,5 +64,20 @@ public class JoinerSplitterUnitTest {
assertEquals(result, expectation);
}
@Test
public void givenStringArray_transformedToStream_convertToMap() {
String[] programming_languages = new String[] {"language:java","os:linux","editor:emacs"};
Map<String,String> expectation=new HashMap<>();
expectation.put("language", "java");
expectation.put("os", "linux");
expectation.put("editor", "emacs");
Map<String, String> result = JoinerSplitter.arrayToMap(programming_languages);
assertEquals(result, expectation);
}
}