2 回答

TA貢獻1155條經驗 獲得超0個贊
使用 aStream來避免臨時狀態。
final Map<String, String> output =
input.entrySet()
.stream()
.collect(Collectors.toMap(
o -> o.getKey(),
o -> o.getValue().getName()
));
Collectors.toMap接受兩個功能接口作為輸入參數
toMap(Function<? super T, ? extends K> keyMapper, // Returns the new key, from the input Entry
Function<? super T, ? extends U> valueMapper // Returns the new value, from the input Entry
) { ... }
要處理該用例,您需要創建一個新的、簡化的用戶表示。
public class SimpleUser {
public final String id;
public final String name;
public final String country;
private SimpleUser(
final String id,
final String name,
final String country) {
this.id = id;
this.name = name;
this.country = countr;
}
public static SimpleUser of(
final String id,
final String name,
final String country) {
return new SimpleUser(id, name, country);
}
}
比你剛剛
.collect(Collectors.toMap(
o -> o.getKey(),
o -> {
final User value = o.getValue();
return SimpleUser.of(user.getId(), user.getName(), user.getCountry());
}
));

TA貢獻1828條經驗 獲得超3個贊
這個答案使用Java Streams。該collect方法可以接受一個Collector. 這個取每一(Integer, User)對并創建一(Integer, UserV2)對。
Map<Integer, UserV2> userIdToUserV2 = users.entrySet().stream()
// Map (Integer, User) -> (Integer, UserV2)
.collect(Collectors.toMap(
// Use the same Integer as the map key
Map.Entry::getKey,
// Build the new UserV2 map value
v -> {
User u = v.getValue();
// Create a UserV2 from the User values
return new UserV2(u.getId(), u.getName(), u.getCountry());
}));
添加回答
舉報