亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從地圖中的對象中刪除某些元素

從地圖中的對象中刪除某些元素

qq_花開花謝_0 2022-06-23 19:59:54
我有一個對象地圖Map<Integer, User>其中用戶的 id 映射到具有 id、firstName、lastName、Name、email、zipCode、country、state 的 User 對象如何將其簡化為只有 id 和 name 的 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、name 和 country 的 UserV2 類
查看完整描述

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());

       }

));


查看完整回答
反對 回復 2022-06-23
?
倚天杖

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());

        }));


查看完整回答
反對 回復 2022-06-23
  • 2 回答
  • 0 關注
  • 118 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號