猿问

如何在 Java 8 中从管道分离的 CSV 返回地图

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;

}

想知道如何使用 Java8 流重写它?


MM们
浏览 131回答 2
2回答

紫衣仙女

您需要流式传输拆分数组,用于map操作它并最终将其收集到地图中:return Arrays.stream(reports.split( "," ))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.map(s-> s.split("|"))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.collect(Collectors.toMap(p-> Long.parseLong(p[0]), p-> p[1]));

弑天下

地图 - 不允许重复键。也请查看下面的代码。我认为它也可能对您有所帮助或为您提供更多信息。我已将输入源字符串更改为1234345|str1,1234346|str2,1234347|str3并更新了额外的行,尤其是sysout打印内存值。String source = "1234345|str1,1234346|str2,1234347|str3";&nbsp; &nbsp; return Arrays.stream(source.split(","))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(s -> s.split("\\|"))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(&nbsp; Collectors.toMap ( s -> { System.out.println(" 1: "+Long.valueOf ( s[0]));&nbsp; return Long.valueOf ( s[0]);} ,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; s -> { System.out.println(" 2: "+s[1]);return s[1]; },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ( (v1, v2) -> {&nbsp; &nbsp;System.out.println("------ line 131 : "+v1 +"&nbsp; "+v2); return v2 ;}&nbsp; )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;);使用上述来源,您将获得输出: {1234346=str2, 1234347=str3, 1234345=str1}如果我将源更改为source = "123434|str1,123434|str2,123434|str3",则输出为{123434=str3}
随时随地看视频慕课网APP

相关分类

Java
我要回答