代码之家  ›  专栏  ›  技术社区  ›  Jigar Naik

包含另一个地图的java8 genrate地图

  •  1
  • Jigar Naik  · 技术社区  · 6 年前

    如何使用Java=8实现这一点

    我有一个以下格式的csv,从中我想填充地图 外部地图将在哪里有键 scriptId transationType 因为这些是独特的 Type 和内部地图 斯克里蒂德 键应该包含前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;
        };
    
    1 回复  |  直到 6 年前
        1
  •  3
  •   Flown    6 年前

    嗯,用两个要简单得多 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])));