Java8生成包含另一个Map的Map

时间:2019-02-12 08:36:07

标签: java-8

我如何使用java = 8做到这一点

我有以下格式的CSV,因此我想从中填充Map 其中外部映射将具有键scriptIdtransationType,因为它们是截然不同的Type,而scriptId密钥的内部映射应包含从位置2开始作为键的前5个值,并且3作为价值。

<scriptId<
      <TATA,TATA Moters>
      <REL,Reliance Industries Ltd>
      <LNT, L&T>
      <SBI, State Bank of India>>
 <transactionType,<
       <P,B>
       <S,S>>

CSV文件的内容

Type,ArcesiumValue,GICValue
scriptId,TATA,TATA Moters
scriptId,REL,Reliance Industries Ltd
scriptId,LNT,L&T
scriptId,SBI,State Bank of India
transactionType,P,B
transactionType,S,S

如何使用Java8生成它

public void loadReferenceData() throws IOException {

        List<Map<String, Map<String, String>>> cache = Files.lines(Paths.get("data/referenceDataMapping.csv")).skip(1)
                .map(mapRefereneData).collect(Collectors.toList());

        System.out.println(cache);

    }

    public static Function<String, Map<String, Map<String, String>>> mapRefereneData = (line) -> {
        String[] sp = line.split(",");
        Map<String, Map<String, String>> cache = new HashMap<String, Map<String, String>>();
        try {
            if (cache.containsKey(sp[0])) {
                cache.get(sp[0]).put(sp[1], sp[2]);
            } else {
                Map<String, String> map = new HashMap<String, String>();
                map.put(sp[1], sp[2]);
                cache.put(sp[0], map);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return cache;
    };

1 个答案:

答案 0 :(得分:3)

使用两个Collectors更简单:

Map<String, Map<String, String>> groupCSV = Files.lines(Paths.get("..."))
    .skip(1L).map(l -> l.split(","))
    .collect(Collectors.groupingBy(a -> a[0], Collectors.toMap(a -> a[1], a -> a[2])));