如何在Java

时间:2018-12-13 11:23:34

标签: java hashmap

我想在字符串下面分割

  

G04:AMPARAMS | DCode = 50 | XSize = 66mil | YSize = 66mil | CornerRadius = 0mil | HoleSize = 0mil |用法= FLASHONLY | Rotation = 0.000 | XOffset = 0mil | YOffset = 0mil | HoleType = Round | Shape = Octagon | *

我首先是从'|'管道符号中分离出代码,然后又从'='等号中分离出来,但是我现在面临的问题是如何将值存储在哈希图中,因为它们处于循环状态,所以我不能将其存储在哈希图中。任何可能的解决方案都适用。

String[] temp=line.split("\\|");
for(String p:temp){
    HashMap<String,String>attributes=new HashMap<String,String>();
    String[] key =p.split("\\=");

    for(String tmp:key){
    //System.out.println(tmp);
    attributes.put();
    }

3 个答案:

答案 0 :(得分:3)

通过流更容易做到这一点:

@EnableTransactionManagement
  • Arrays.stream(input.split("\\|")) .map(s -> s.split("=")) .filter(a -> a.length == 2) .collect(toMap(a -> a[0], a -> a[1], (l, r) -> r, HashMap::new)); 创建一个Arrays.stream,然后我们可以通过几个built-in stream API methods进一步优化查询。
  • Stream<String>在“ =”上拆分每个字符串,因此返回map
  • Stream<String[]>保留恰好具有两个元素的数组元素
  • 最后,我们向filter方法提供了toMap收集器,以构建collect

答案 1 :(得分:3)

无流:

public static Map<String, String> split(String str) {
    final Pattern sep = Pattern.compile("\\s*\\|\\s*");
    final Pattern eqSep = Pattern.compile("(?<key>[^=\\s]+)\\s*=\\s*(?<value>[^=]+)");

    Map<String, String> map = new HashMap<>();

    for (String part : sep.split(str)) {
        Matcher matcher = eqSep.matcher(part);

        if (matcher.matches())
            map.put(matcher.group("key"), matcher.group("value"));
    }

    return map;
}

使用流:

public static Map<String, String> split(String str) {
    final Pattern sep = Pattern.compile("\\s*\\|\\s*");
    final Pattern eqSep = Pattern.compile("(?<key>[^=\\s]+)\\s*=\\s*(?<value>[^=]+)");

    return sep.splitAsStream(str)
              .map(eqSep::matcher)
              .filter(Matcher::matches)
              .collect(Collectors.toMap(matcher -> matcher.group("key"), matcher -> matcher.group("value")));
}

答案 2 :(得分:1)

看起来您需要的是:

like[pdf,xlsx,image]

请注意,由于要将所有键值对存储在同一String[] temp = line.split("\\|"); Map<String,String> attributes = new HashMap<String,String>(); for (String p : temp) { String[] key = p.split("\\="); if (key.length == 2) { attributes.put(key[0],key[1]); } } 中,因此应在循环外部创建一个HashMap

相关问题