[英]List of String to Map Java8
I have a list of String in my application.我的应用程序中有一个字符串列表。 Every String is actually an output of 2 different strings concatenated by ".".每个字符串实际上是由“.”连接的 2 个不同字符串的输出。 eg Stack.Overflow例如 Stack.Overflow
Now, I am trying to convert this list to a Map with key being the first part of the string and value being the second part.现在,我试图将此列表转换为 Map,键是字符串的第一部分,值是第二部分。 eg key=Stack and value=Overflow例如 key=Stack 和 value=Overflow
I am doing something like this:我正在做这样的事情:
List<String> sampleList = someList here;
Map<String, String> outputMap= sampleList .stream().collect(
Collectors.toMap(s->s.toString().split("\\.")[0],
s->s.toString().split("\\.")[1]));
How can it be achieved?如何实现? Thanks谢谢
It doesn't seem to be working for me.它似乎对我不起作用。 See below:见下文:
List<String> sample = new ArrayList<>();
sample.add("12345.22-JUN-18");
sample.add("12345.22-JUN-18");
sample.add("45678.25-JUN-18");
sample.add("23456.25-JUN-18");
sample.add("34567.25-JUN-18");
sample.add("67890.25-JUN-18");
sample.add("45678.25-JUN-18");
sample.add("23456.26-JUN-18");
Pattern pattern = Pattern.compile("[.]");
Map<String,String> output = sample.stream()
.map(pattern::split)
.collect(Collectors.toMap(s -> s[0], s -> s[1]));
It gives me java.lang.IllegalStateException: Duplicate key 22-JUN-18.
Why is it taking the date as the key?为什么以日期为关键? It should have the date as the value not as a key.它应该将日期作为值而不是键。
I think what you have there is fine, assuming \\\\.
我认为你在那里的东西很好,假设\\\\.
matches the single character .
匹配单个字符.
. .
However, you can clean it up a bit by compiling the regex into a Pattern
and using Stream#map
:但是,您可以通过将正则表达式编译为Pattern
并使用Stream#map
来清理它:
Pattern pattern = Pattern.compile("[.]");
Arrays.asList("Stack.Overflow")
.stream()
.map(pattern::split)
.collect(Collectors.toMap(s -> s[0], s -> s[1]));
Output:输出:
{Stack=Overflow}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.