[英]Get all the values of single key from the list map java8
我的清單如下:
List<Map<String,Object>> mapList=new ArrayList<>();
Map<String,Object> mapObject=new HashMap<String,Object>();
mapObject.put("No",1);
mapObject.put("Name","test");
mapList.add(mapObject);
Map<String,Object> mapObject1=new HashMap<String,Object>();
mapObject1.put("No",2);
mapObject1.put("Name","test");
mapList.add(mapObject1);
and so on...
現在,我想獲取鍵“ No”的所有值作為用逗號分隔的字符串,如下所示:
String noList="1,2,3"
任何人都可以建議我什么是最好的方法。 我知道我們可以通過循環來做到這一點,但是除了循環之外,其他任何方式也可以做到這一點。
內聯說明!
mapList.stream() // stream over the list
.map(m -> m.get("No")) // try to get the key "No"
.filter(Objects::nonNull) // filter any null values in case it wasn't present
.map(Object::toString) // call toString for each object
.collect(Collectors.joining(",")); // join the values
只需映射列表:
String list = mapList.stream()
.filter(x -> x.containsKey("No")) // get only the maps that has the key
.map(x -> x.get("No").toString()) // every map will be transformed like this
.collect(Collectors.joining(",")); // joins all the elements with ","
System.out.println(list);
HashMap<String, Object>
表明為該數據創建一個新類可能更好。 您之前考慮過這種可能性嗎?
您可以像這樣循環:
List<String> noList = new ArrayList<>(mapList.size());
for (Map<String,Object> m : mapList) {
Optional.ofNullable(m.get("No")) // get value mapped to "No" or empty Optional
.map(Object::toString)
.ifPresent(noList::add); // if not empty, add to list
}
System.out.println(String.join(",", noList));
或內部(官方首選版本IIRC):
List<String> noList = new ArrayList<>(mapList.size());
mapList.forEach(m ->
Optional.ofNullable(m.get("No")).map(Object::toString).ifPresent(noList::add));
System.out.println(String.join(",", noList));
現在我想到了,它比Stream
版本短。
30分鍾前回答了一個非常類似的問題。
您正在使用重復鍵。 這使您看起來好像不需要映射,而是一個具有屬性“ No”,“ Name”等的類。如果您具有此類,則可以僅在列表上迭代實例並串聯為String。
如果無論您想擁有什么地圖,只需獲取“ No”鍵的值即可,但是請注意,這是錯誤的做法,您可能應該使用類而不是地圖:
String res = "";
for(int i = 0; i < mapList.size(); i++) {
Map<String,Object> map = mapList.get(i);
res.concat(map.get("No"));
if(i != mapList.size() - 1)
res.concat(",");
}
PS:如果您使用的是不好的解決方案,那么,如果您對流的了解足以理解它們,請在其他答案中使用流替代方案。
試試看
String concatValues = mapList.stream().map(map -> String.valueOf(map.get("No")))
.collect(Collectors.joining(","));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.