gpt4 book ai didi

java - 如何将 list 转换为保留所有重复键和值的映射

转载 作者:行者123 更新时间:2023-12-01 17:46:48 25 4
gpt4 key购买 nike

我有一个列表如下:

List<Address> address;

哪里

Address:
city
country
state

我想将其转换为如下所示

Map <String,String> convertedMap=list.stream().collect
(Collectors.toMap(Address:getCity+Address:getCountry ,Address:getState));

我想在生成的映射中保留所有重复的键和值,如下所示。

(key=City1country1, value= state1) ,(key=City1country1, value=state2),(key=City1country1,value= state1) ;

最佳答案

正如评论中提到的, map 不存储重复的键,因此您必须使用 Map<String, List<String>>相反 Map<String, String>

总而言之,您只需使用 Collectors.toMap方法 mergeFunction您可以在其中处理重复键的参数。每次出现相同的按键时都会调用该操作。在本例中,我们只需将两个列表合并为一个。看一下下面的代码(使用 JDK 11 编译),我相信它完全满足您的需要并打印预期结果(当然使用 List<String>)。

import java.util.*;
import java.util.stream.Collectors;

public class ListToMapWithDuplicatedKeysSample {

public static void main(String[] args) {
List<Address> addresses = List.of(
new Address("City1", "country1", "state1"),
new Address("City1", "country1", "state2"),
new Address("City1", "country1", "state1"),
new Address("City3", "country3", "state3")
);
Map<String, List<String>> result = addresses.stream()
.collect(
Collectors.toMap(
address -> address.getCity() + address.getCountry(),
address -> Collections.singletonList(address.getState()),
ListToMapWithDuplicatedKeysSample::mergeEntriesWithDuplicatedKeys
)
);
System.out.println(result);
}

private static List<String> mergeEntriesWithDuplicatedKeys(List<String> existingResults, List<String> newResults) {
List<String> mergedResults = new ArrayList<>();
mergedResults.addAll(existingResults);
mergedResults.addAll(newResults);
return mergedResults;
}

private static class Address {

private final String city;
private final String country;
private final String state;

public Address(String city, String country, String state) {
this.city = city;
this.country = country;
this.state = state;
}

String getState() {
return state;
}

String getCountry() {
return country;
}

String getCity() {
return city;
}
}
}

关于java - 如何将 list<SomeType> 转换为保留所有重复键和值的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54281167/

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