我有一个对象 map
Map<Integer, User>
其中用户的 id 映射到具有 id、firstName、lastName、Name、email、zipCode、country、state 的 User 对象
如何将其简化为只有 id 和名称的 map ,其他用户信息无关。
--编辑
抱歉,我的问题不清楚,我基本上想从
0 : {id: 0, name: 'test0', country: 'us', firstName: 'ft0', lastName: 'lt0'},
1 : {id: 1, name: 'test1', country: 'us', firstName: 'ft1', lastName: 'lt1'},
2 : {id: 2, name: 'test2', country: 'us', firstName: 'ft2', lastName: 'lt2'}
至
0 : {id: 0, name: 'test0', country: 'us'},
1 : {id: 1, name: 'test1', country: 'us'},
2 : {id: 2, name: 'test2', country: 'us'}
我还有一个包含所有用户属性的 User 类和一个仅包含 id、名称和国家/地区的 UserV2 类
最佳答案
使用Stream
来避免临时状态。
final Map<String, String> output =
input.entrySet()
.stream()
.collect(Collectors.toMap(
o -> o.getKey(),
o -> o.getValue().getName()
));
Collectors.toMap
接受两个功能接口(interface)作为输入参数
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());
}
));
关于java - 从映射中的对象中删除某些元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54755620/