如何使用Stream流操作将list中所有map的某个值拼接成字符串?
将list中所有所有map的某个值用逗号隔开拼接成字符串,但是写的语句却报错了。
相关代码
List<Map> list =new ArrayList<>();
Map<String,String> m =new HashMap(); m.put("name","樟树街");
Map<String,String> m1 =new HashMap();
m.put("name","樟树街1");
Map<String,String> m2 =new HashMap();
m.put("name","樟树街1");
list.add(m);
list.add(m2);
list.add(m1);
//想把map中每一个名字用逗号隔开拼接个字符串,如果list中不是map而是个具体的实体则没问题
String s= list.stream().map(p->p.get("name")).collect(Collectors.joining(","));
list.stream().map(p->p.get("name")).collect(Collectors.joining(",")); 会报错,请问要实现功能应该怎么写呢?
回答:
Map<String,String> m =new HashMap(); m.put("name","樟树街");
Map<String,String> m1 =new HashMap();
m.put("name","樟树街1");
Map<String,String> m2 =new HashMap();
m.put("name","樟树街1");
这一段内容插入的都在m里面....
修改后
package com.huifer.concurrence.issues;import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class C {
public static void main(String[] args) {
List<Map<String, String>> list = new ArrayList<>();
Map<String, String> m = new HashMap();
m.put("name", "樟树街");
Map<String, String> m1 = new HashMap();
m1.put("name", "樟树街1");
Map<String, String> m2 = new HashMap();
m2.put("name", "樟树街1");
list.add(m);
list.add(m2);
list.add(m1);
String s= list.stream().map(p->p.get("name")).collect(Collectors.joining(","));
System.out.println(s);
}
}
回答:
没毛病啊这代码。
public static void main(String[] args) { List<Map<String, String>> list = new ArrayList<>(3);
Map<String, String> m = new HashMap<>(1);
m.put("name", "樟树街");
Map<String, String> m1 = new HashMap<>(1);
m1.put("name", "樟树街1");
Map<String, String> m2 = new HashMap<>(1);
m2.put("name", "樟树街2");
list.add(m);
list.add(m1);
list.add(m2);
String s = list.stream()
.map(p -> p.get("name"))
.collect(Collectors.joining(","));
System.out.println(s);
}
Output:
樟树街,樟树街1,樟树街2
以上是 如何使用Stream流操作将list中所有map的某个值拼接成字符串? 的全部内容, 来源链接: utcz.com/p/180104.html