1
public Map<Long, String> getReports()
{
    // 123434|str1,123434|str2,123434|str3
    HashMap<Long, String> map = new HashMap<Long, String>();
    List<String> items =  Arrays.asList( reports.split( "," ) );
    for( String i : items )
    {
        String parts[] = i.split( "|" );
        map.put( Long.parseLong( parts[0] ), parts[1] );
    }
    return map;
}

Wondering how would I rewrite this using Java8 streams?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Squiggs.
  • 4,299
  • 6
  • 49
  • 89
  • 2
    Have you read https://stackoverflow.com/q/10796160/1225328 already? `.split("|")` isn't behaving the way you expect. Is your current code working? – sp00m Sep 19 '18 at 11:18
  • `return Arrays.stream(reports.split(",")) .map(i -> i.split("|")) // check this .collect(Collectors.toMap(parts -> Long.parseLong(parts[0]), parts -> parts[1], (a, b) -> b, HashMap::new));` – Naman Sep 19 '18 at 11:19

2 Answers2

3

You need to stream the split array, use map to manipulate it and collect it to a map in the end:

return Arrays.stream(reports.split( "," ))
             .map(s-> s.split("|"))
             .collect(Collectors.toMap(p-> Long.parseLong(p[0]), p-> p[1]));
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 1
    worth to note https://stackoverflow.com/questions/52404605/how-to-return-a-map-from-a-pipe-separate-csv-in-java-8#comment91752917_52404605 – Naman Sep 19 '18 at 12:08
0

@Squiggs: A Map - doesn't allow duplicate keys. please look into below code, also. I thought it might also help you OR give you little more information. I have changed the input source string to 1234345|str1,1234346|str2,1234347|str3 and updated with extra lines, especially sysout to print the memory values.

String source = "1234345|str1,1234346|str2,1234347|str3";

    return Arrays.stream(source.split(","))
            .map(s -> s.split("\\|"))
            .collect(  Collectors.toMap ( s -> { System.out.println(" 1: "+Long.valueOf ( s[0]));  return Long.valueOf ( s[0]);} ,
                                          s -> { System.out.println(" 2: "+s[1]);return s[1]; },
                                          ( (v1, v2) -> {   System.out.println("------ line 131 : "+v1 +"  "+v2); return v2 ;}  )
                                        )
                     );

with the above source you get output as: {1234346=str2, 1234347=str3, 1234345=str1}

If I change the source to source = "123434|str1,123434|str2,123434|str3", I get the output as {123434=str3}

MKod
  • 803
  • 5
  • 20
  • 33