gpt4 book ai didi

java - 在复杂的 HashMap 中使用 StringJoiner

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:00:12 26 4
gpt4 key购买 nike

我有如下 map 列表:

List<Map<String,Object>> someObjectsList = new ArrayList<Map<String,Object>>();

我将以下数据存储在每个 HashMap 中

key             value
2017-07-21 2017-07-21-07.33.28.429340
2017-07-24 2017-07-24-01.23.33.591340
2017-07-24 2017-07-24-01.23.33.492340
2017-07-21 2017-07-21-07.33.28.429540

我想遍历 HashMap 列表并检查键是否与任何 HashMap 值的前 10 个字符匹配,然后我想存储这些键和值采用以下格式。即通过使用遥测“逗号”。最终目标是将 HashMap 的唯一键及其相对值(如果键与任何 HashMap 值的前 10 个字符匹配)分组到一个新的 HashMap 中。

key          value
2017-07-21 2017-07-21-07.33.28.429340,2017-07-21-07.33.28.429540
2017-07-24 2017-07-24-01.23.33.591340,2017-07-24-01.23.33.492340

我正在尝试使用 StringJoiner 跟踪 java 代码,但没有得到预期的结果。关于如何在此处构建逻辑的任何线索?

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;

public class SampleOne {

public static void main(String[] args) {
// TODO Auto-generated method stub
List<Map<String, Object>> someObjectsList = new ArrayList<Map<String, Object>>();

Map<String, Object> mapOne = new HashMap<String, Object>();
mapOne.put("2017-07-21", "2017-07-21-07.33.28.429340");

Map<String, Object> mapTwo = new HashMap<String, Object>();
mapTwo.put("2017-07-24", "2017-07-24-01.23.33.591340");

Map<String, Object> mapThree = new HashMap<String, Object>();
mapThree.put("2017-07-24", "2017-07-24-01.23.33.492340");

Map<String, Object> mapFour = new HashMap<String, Object>();
mapFour.put("2017-07-21", "2017-07-21-07.33.28.429540");

someObjectsList.add(mapOne);
someObjectsList.add(mapTwo);
someObjectsList.add(mapThree);
someObjectsList.add(mapFour);

for (Map map : someObjectsList) {
StringJoiner sj = new StringJoiner(",");
for (Object key : map.keySet()) {
String value = ((String) map.get(key));
String date = value.substring(0, Math.min(value.length(), 10));
//System.out.println(str);
//System.out.println(value);

if(key.equals(date)) {
sj.add(value);
System.out.println(sj.toString());
}
}

}

}

}

输出:

2017-07-21-07.33.28.429340
2017-07-24-01.23.33.591340
2017-07-24-01.23.33.492340
2017-07-21-07.33.28.429540

最佳答案

利用.merge功能:

Map<String, Object> finalMap = new HashMap<String, Object>();

for (Map map : someObjectsList) {
for (Object key : map.keySet()) {
String value = ((String) map.get(key));
finalMap.merge((String) key, value, (k, v) -> k + "," + v);
}
}

哪些输出:

{2017-07-21=2017-07-21-07.33.28.429340,2017-07-21-07.33.28.429540, 2017-07-24=2017-07-24-01.23.33.591340,2017-07-24-01.23.33.492340}


同样可以通过下面的一行实现:

someObjectsList.stream()
.flatMap(i -> i.entrySet().stream())
.collect(Collectors.toMap(Entry::getKey, Entry::getValue,
(k, v) -> k + "," + v));

关于java - 在复杂的 HashMap 中使用 StringJoiner,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56164596/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com