Search code examples
javalambdajava-8java-streamfunctional-interface

List of String to Map Java8


I have a list of String in my application. Every String is actually an output of 2 different strings concatenated by ".". e.g. Stack.Overflow

Now, I am trying to convert this list to a Map with key being the first part of the string and value being the second part. e.g key=Stack and value=Overflow

I am doing something like this:

List<String> sampleList = someList here;

Map<String, String> outputMap= sampleList .stream().collect(
            Collectors.toMap(s->s.toString().split("\\.")[0],
s->s.toString().split("\\.")[1]));

How can it be achieved? Thanks

It doesn't seem to be working for me. See below:

List<String> sample = new ArrayList<>();
    sample.add("12345.22-JUN-18");
    sample.add("12345.22-JUN-18");
    sample.add("45678.25-JUN-18");

    sample.add("23456.25-JUN-18");
    sample.add("34567.25-JUN-18");
    sample.add("67890.25-JUN-18");
    sample.add("45678.25-JUN-18");
    sample.add("23456.26-JUN-18");

    Pattern pattern = Pattern.compile("[.]");

    Map<String,String> output = sample.stream()
      .map(pattern::split)
      .collect(Collectors.toMap(s -> s[0], s -> s[1]));

It gives me java.lang.IllegalStateException: Duplicate key 22-JUN-18.

Why is it taking the date as the key? It should have the date as the value not as a key.


Solution

  • I think what you have there is fine, assuming \\. matches the single character ..

    However, you can clean it up a bit by compiling the regex into a Pattern and using Stream#map:

    Pattern pattern = Pattern.compile("[.]");
    
    Arrays.asList("Stack.Overflow")
          .stream()
          .map(pattern::split)
          .collect(Collectors.toMap(s -> s[0], s -> s[1]));
    

    Output:

    {Stack=Overflow}