Java8生成包含地图另一个地图

问题描述 投票:1回答:1

如何实现这一目标用java = 8

我有一个CSV在下面的格式和从本我要填充Map<String, Map<String, String>其中外地图将具有键scriptIdtransationType因为这些是不同Type和内部的地图为scriptId键应该包含第一5个值从位置2,说明作为键和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;
    };
java-8
1个回答
4
投票

那么它是更加简单使用两个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])));
© www.soinside.com 2019 - 2024. All rights reserved.