我有一个字符串数组列表,例如:
ArrayList<String> result = new ArrayList<String>() ;
result.add("Name.A");
result.add("Name.B");
result.add("Name.C");
result.add("Type.D");
result.add("Type.E");
result.add("Type.F");
现在我需要将其转换为 HashMap,其中一个键(点之前)为多个值(点之后)。
像这样:Map<String,String[]> map = new HashMap<>();
map (名称= A,B,C)
map (类型= D、E、F)
不知道该怎么做。任何帮助将不胜感激
Response response
= given().
relaxedHTTPSValidation().
accept(ContentType.JSON).
when().
urlEncodingEnabled(true).
get(uri).
then().
extract().response();
List<String> actual = response.jsonPath().getList("RESPONSE.A_VALUE");
Map<String, String[]> map = new HashMap<>();
for (String pair : actual) //iterate over the pairs
{
if (pair.contains(".")) {
String[] pair_values = pair.split("\\.");
map.put(pair_values[0].trim(), pair_values[1].trim());
}
}
最佳答案
使用 Java 8 流
ArrayList<String> result = new ArrayList<String>() ;
result.add("Name.A");
result.add("Name.B");
result.add("Name.C");
result.add("Type.D");
result.add("Type.E");
result.add("Type.F");
Map<String, List<String>> returnValue = result.stream()
.map(p -> p.split("\\.", 2))
.filter(p -> p.length == 2)
.collect(
Collectors.groupingBy(
p -> p[0],
Collectors.mapping(
p -> p[1],
Collectors.toList())));
System.out.println(returnValue);
这会将值按点分成最多 2 组,然后按第一部分对值进行分组。
关于java - 如何使用由 .dot 分割的字符串 ArrayList 中的一个键和多个值填充 hashmap?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46911830/