我正在使用
Stream
学习 Java,我有一个 Map<String, List<Customer>> map1
,我想将它映射到 Map<String, List<CustomerObj>> map2
。如何使用 Java Stream API 执行此操作?
您可以使用按键映射器
stream
map1
Collectors.toMap
的条目并使用 Map.Entry::getKey
进行收集。对于值映射器,您可以获取条目值列表,然后stream
并从Customer
映射到CustomerObj
,最后收集到List
。
这里是使用
Integer
代替 Customer
和 String
代替 CustomerObj
的示例:
Map<String, List<Integer>> map1 = Map.of(
"A", List.of(1, 2),
"B", List.of(3, 4),
"C", List.of(5, 6));
Map<String, List<String>> map2 = map1.entrySet().stream().collect(
Collectors.toMap(Map.Entry::getKey,
entry -> entry.getValue().stream()
.map(String::valueOf).toList()));
你可以这样做:
Customer c1 = new Customer("İsmail", "Y.");
Customer c2 = new Customer("Elvis", "?.");
Map<String, List<Customer>> customerList = new HashMap<>();
customerList.put("U1", Arrays.asList(c1));
customerList.put("U2", Arrays.asList(c1, c2));
Map<String, List<CustomerObj>> customerObjList = customerList
.entrySet().stream().collect(
Collectors.toMap(Map.Entry::getKey,
entry -> entry.getValue().stream()
.map(CustomerObj::new)
// or .map(c -> new CustomerObj(c))
.collect(Collectors.toList())
)
);
}
private static class Customer {
private String firstName;
private String lastName;
public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}
private static class CustomerObj {
private String fullName;
public CustomerObj(Customer customer) {
this.fullName = String.join(" ",
customer.getFirstName(), customer.getLastName()
);
}
public String getFullName() {
return fullName;
}
}
@Oboe 的答案适用于
Java 16+
,这个答案与您的模型类似,更容易理解。