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

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

如何將單個鍵值添加到現有的 Java 8 流?

如何將單個鍵值添加到現有的 Java 8 流?

人到中年有點甜 2023-02-23 18:13:38
這是我填充靜態地圖的方法public static final Map<String, FooBar> mapEnum = Arrays.stream(FooBarEnum.values())            .collect(Collectors.toMap(e-> StringUtils.upperCase(e.name), e -> e));我想向這張地圖添加另一個鍵值對。mapEnum.put("xx", FooBar.A);這是枚舉public enum FooBar {   A("a"), B("b"), C("c");}構建地圖后,我的靜態地圖將如下所示{"a":FooBar.A, "b": FooBar.B, "c": FooBar.C, "xx": Foobar.A}是否可以將顯式 put 調用包括在內Collectors.toMap()?
查看完整描述

4 回答

?
手掌心

TA貢獻1942條經驗 獲得超3個贊

如果您愿意使用第三方庫,則可以使用Eclipse CollectionsImmutableMap創建靜態內聯。Stream


public?static?final?ImmutableMap<String,?FooBar>?MAP_ENUM?=
????????Arrays.stream(FooBar.values())
????????????????.collect(Collectors2.toMap(FooBar::getName,?fooBar?->?fooBar))
????????????????.withKeyValue("xx",?FooBar.A)
????????????????.toImmutable();public?enum?FooBar?{
????A("a"),?B("b"),?C("c");????private?String?name;

????FooBar(String?name)?{????????this.name?=?name;
????}????public?String?getName()?{????????return?this.name;
????}
}

您還可以使用本機 Eclipse Collections API 稍微簡化代碼。

public?static?final?ImmutableMap<String,?FooBar>?MAP_ENUM?=
????????ArrayAdapter.adapt(FooBar.values())
????????????????.groupByUniqueKey(FooBar::getName)
????????????????.withKeyValue("xx",?FooBar.A)
????????????????.toImmutable();




查看完整回答
反對 回復 2023-02-23
?
莫回無

TA貢獻1865條經驗 獲得超7個贊

實際上,我認為沒有必要為此使用 Java Streams。您可以簡單地使用該static塊來初始化mapEnum它put的附加值:


public static final Map<String, FooBar> mapEnum;


static {

    mapEnum = Arrays.stream(FooBar.values())

            .collect(Collectors.toMap(FooBar::getName, Function.identity()));

    mapEnum.put("xx", FooBar.A);

    // ...

}

Collectors.toMap():不保證返回的 {@code Map} 的類型、可變性、可序列化性或線程安全性。


Map為了確保返回的可變性Collectors.toMap(),以便您Map.put()以后可以更好地使用它:


Arrays.stream(FooBar.values())

        .collect(Collectors.toMap(Function.identity(), Function.identity(), (a, b) -> a, HashMap::new));

如果你真的想使用 java 流,你可以使用這個:


public static final Map<String, FooBar> mapEnum = Stream.concat(

        Stream.of(FooBar.values()).map(e -> Map.entry(e.getName(), e)),

        Stream.of(Map.entry("xx", FooBar.A))

).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

或者,如果您還想將所有名稱添加到枚舉值本身,您可以像這樣更改您的類:


public static enum FooBar {

    A("a", "xx"), B("b"), C("c");


    private String[] names;


    FooBar(String... names) {

        this.names = names;

    }


    public String[] getNames() {

        return names;

    }

}

并使用它來創建地圖:


public static final Map<String, FooBar> mapEnum = Stream.of(FooBar.values())

        .flatMap(e -> Arrays.stream(e.getNames()).map(n -> Map.entry(n, e)))

        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

在 Java 9 之前使用new AbstractMap.SimpleEntry<>()而不是Map.entry(). 如果您需要對地圖進行排序,請LinkedHashMap::new使用Collectors.toMap().


查看完整回答
反對 回復 2023-02-23
?
qq_花開花謝_0

TA貢獻1835條經驗 獲得超7個贊

您可以使用Collectors::collectAndThen修改結果地圖

Arrays.stream(FooBarEnum.values())
        .collect(Collectors.collectAndThen(
                    Collectors.toMap(e-> StringUtils.upperCase(e.name), 
                        Function.identity()), FooBarEnum::addCustom));

以下方法在枚舉中

static Map<String, FooBar> addCustom(Map<String, FooBarEnum> map) {
    map.put("xx", FooBar.A);
        return map;
}


查看完整回答
反對 回復 2023-02-23
?
千巷貓影

TA貢獻1829條經驗 獲得超7個贊

您不能直接將它傳遞給 Collectors.toMap()。您可以在 javadoc 中看到所有可用的覆蓋:https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#toMap-java.util.function.Function-java .util.function.Function- .


但是,在使用 Stream.concat 調用 toMap 之前,您可以確保您的流具有構建地圖所需的所有對。您連接枚舉中的對,以及要添加的手動對。


我的獨立代碼必須定義 Pair 類,但由于您使用了 StringUtils,我想您有一個已經包含 Pair 的庫,因此您不需要定義它。


代碼:


import java.util.*;

import java.util.stream.*;


public class Main {


    private static enum  FooBar {

        A("a"), B("b"), C("c");

        private String name;

        FooBar(String name) {

            this.name = name;

        }

    }


    public static class Pair {

        String a;

        FooBar b;

        Pair(String a, FooBar b) {

            this.a = a;

            this.b = b;

        }

    }


    public static void main(String [] args) {

        System.out.println(

            Stream.concat( 

                Arrays.stream(FooBar.values()).map(e -> new Pair(e.name.toUpperCase(), e)),

                Stream.of(new Pair("xx", FooBar.A))

            )

            .collect(Collectors.toMap(pair -> pair.a, pair -> pair.b))

        );

    }


}

輸出:


{xx=A, A=A, B=B, C=C}


查看完整回答
反對 回復 2023-02-23
  • 4 回答
  • 0 關注
  • 154 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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