String Manipulation in Java 8 Threads

I have a stream of strings, Token1:Token2:Token3 Here ':'is a separator character. Here Token3String may contain a delimiter character or may be absent. We need to convert this stream to a map using Token1 as the key, and value is an array of two lines - array[0] = Token2and array[1] = Token3, if present Token3, otherwise null. I tried something like -

return Arrays.stream(inputArray)
            .map( elem -> elem.split(":"))
            .filter( elem -> elem.length==2 )
            .collect(Collectors.toMap( e-> e[0], e -> {e[1],e[2]}));

But that did not work. In addition, it does not handle the case if Token3 is missing or contains a delimiter character.

How can I accomplish this in Java8 lambda expressions?

+4
source share
2 answers

Matcher, , toMap, Matcher.group():

Map<String, String[]> map = Arrays.stream(inputArray)
    .map(Pattern.compile("([^:]++):([^:]++):?(.+)?")::matcher)
    .filter(Matcher::matches)
    .collect(Collectors.toMap(m -> m.group(1), m -> new String[] {m.group(2), m.group(3)}));

:

String[] inputArray = {"Token1:Token2:Token3:other",
        "foo:bar:baz:qux", "test:test"};
Map<String, String[]> map = Arrays.stream(inputArray)
    .map(Pattern.compile("([^:]++):([^:]++):?(.+)?")::matcher)
    .filter(Matcher::matches)
    .collect(Collectors.toMap(m -> m.group(1), m -> new String[] {m.group(2), m.group(3)}));
map.forEach((k, v) -> {
    System.out.println(k+" => "+Arrays.toString(v));
});

:

test => [test, null]
foo => [bar, baz:qux]
Token1 => [Token2, Token3:other]

String.split. , :

Map<String, String[]> map = Arrays.stream(inputArray)
    .map(elem -> elem.split(":", 3)) // 3 means that no more than 3 parts are necessary
    .filter(elem -> elem.length >= 2)
    .collect(Collectors.toMap(m -> m[0], 
                              m -> new String[] {m[1], m.length > 2 ? m[2] : null}));

.

+6

, , :

    return Arrays.stream(inputArray)
            .map(elem -> elem.split(":", 3)) // split into at most 3 parts
            .filter(arr -> arr.length >= 2)  // discard invalid input (?)
            .collect(Collectors.toMap(arr -> arr[0], arr -> Arrays.copyOfRange(arr, 1, 3)));  // will add null as the second element if the array length is 2
+2

All Articles