gpt4 book ai didi

java - Map> 如果键与字符串形式相同,则在运行时将值添加到列表中

转载 作者:行者123 更新时间:2023-11-30 02:27:49 25 4
gpt4 key购买 nike

我有一个字符串,

String value = "Sunday  -  H15,Sunday  -  H03,Sunday  -  H13,Sunday  -  H01,Sunday  -  H05,Friday  -  H23,Saturday  -  H05,Monday  -  H16,Monday  -  H17,Monday  -  H18,Monday  -  H19,Monday  -  H20";

在此字符串中,我们有天(星期日、星期一等),字母数字(H15、H03 等)是小时。

现在我的要求是:

我想要一个Map<String, List<String>>其中Key应为Day,Value应为同一天的Hours列表。

例如:

Sunday : [H15,H03,H13,H01,H05]
Monday : [H16,H17,H18,H19,H20]
Friday : [H23]
Saturday : [H05]

方法:

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

public class DayPartProcessingTest {

public static void main(String[] args) {

String propertyValue = "Sunday - H15,Sunday - H03,Sunday - H13,Sunday - H01,Sunday - H05,Friday - H23,Saturday - H05,Monday - H16,Monday - H17,Monday - H18,Monday - H19,Monday - H20";

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

String[] dayParts = propertyValue.split(",");

for (String string : dayParts) {
String[] array = string.split(" - ");
if (map.get(array[0]) == null) {
List<String> list = new ArrayList<>();
list.add(array[1]);
map.put(array[0], list);
} else {
List<String> tempList = map.get(array[0]);
tempList.add(array[1]);
map.put(array[0], tempList);
}
}
System.out.println(map);

}

}

这工作正常并且符合要求,但是还有其他可能的方法吗?我想不出其他的了:(

最佳答案

试试这个。

String propertyValue = "Sunday  -  H15,Sunday  -  H03,Sunday  -  H13,Sunday  -  H01,Sunday  -  H05,Friday  -  H23,Saturday  -  H05,Monday  -  H16,Monday  -  H17,Monday  -  H18,Monday  -  H19,Monday  -  H20";
Map<String, List<String>> map = new HashMap<String, List<String>>();
String[] dayParts = propertyValue.split(",");
for (String string : dayParts) {
String[] array = string.split(" - ");
map.computeIfAbsent(array[0], k -> new ArrayList<>()).add(array[1]);
}
System.out.println(map);

或者

String propertyValue = "Sunday  -  H15,Sunday  -  H03,Sunday  -  H13,Sunday  -  H01,Sunday  -  H05,Friday  -  H23,Saturday  -  H05,Monday  -  H16,Monday  -  H17,Monday  -  H18,Monday  -  H19,Monday  -  H20";
Map<String, List<String>> map = Arrays.stream(propertyValue.split(","))
.map(e -> e.split(" - "))
.collect(Collectors.groupingBy(
a -> a[0],
Collectors.mapping(a -> a[1], Collectors.toList())));

关于java - Map<String, List<String>> 如果键与字符串形式相同,则在运行时将值添加到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45187787/

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