java - 从映射中的对象中删除某些元素

标签 java object

我有一个对象 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/

相关文章:

java - 如何将分钟添加到循环内的日期

java - 如何找到一个数组的gcd列表,同时忽略0到第n个元素(找到(n-1)个元素的gcd)一个一个?

java - 在 Java 中,如何以简单的方式遍历队列而不破坏它?

java - 非静态API的终结点是什么?

java - 在 Spring 中使用 Twitter4J 获取推文

c++ - 如何对类数组进行排序

javascript - 使用 for 循环附加 onclick 方法

java - 为什么 Object clone() 方法仅适用于实现 Cloneable 接口(interface)的类?

python - 在Python中递归打印对象的所有属性、列表、字典等

javascript - 从字符串解析为对象路径