【问题标题】:How to split value and save into Map java?如何拆分值并保存到 Map java?
【发布时间】:2021-07-12 12:20:49
【问题描述】:

我有一个字符串,它有一些| 分隔值

He run|running|runned quickly, then he|she goes for practice

|分隔值保存在Hashmap中的可能方法是什么 Map<Integer , List<String>> 以便首先存储地图

 1 -> ["run","running","runned"]
 2 -> ["he","she"]

如何实现。拆分此字符串并将值保存在 Map 中的最佳方法是什么。

【问题讨论】:

标签: java


【解决方案1】:

试试这个:

String text = "He run|running|runned quickly, then he|she goes for practice";

// match all the parts which are sequences of words delimited by |
Matcher matcher = Pattern.compile("(\\w+(?:\\|\\w+)+)").matcher(text);

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

// add matches as long as we find any.
while (matcher.find()) {
    map.put(map.size() + 1, 
    // split matches by | and convert them to a list
    Arrays.stream(matcher.group(1).split("\\|")).collect(Collectors.toList()));
}

输出:

map.forEach((k, v) -> 
    System.out.printf("%s = %s\n", k, v.stream().collect(Collectors.joining(","))));

产量:

1 = run,running,runned
2 = he,she

【讨论】:

猜你喜欢
  • 2012-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-24
  • 1970-01-01
相关资源
最近更新 更多