簡體   English   中英

如何創建一個接收隨機鍵和值 java 的 map?

[英]how to create a map that takes in random keys and values java?

我想創建一個 map 來生成隨機數據(它將為每個鍵生成一個隨機值)。 map 用於雙打,這是從練習中得出的,應該被視為替代方案正確答案。 幫助? 我知道 map 的尺寸,但不知道如何生成這些值。 我嘗試了以下代碼:

 public void generateMap(double resolution) {
    String altitude;
    if (resolution == 1) {
        mapOfEarth = new HashMap<>(64800);
    } else if (resolution == 0.5) {
        mapOfEarth = new HashMap<>(259200);
    } else if (resolution == 2) {
        mapOfEarth = new HashMap<>(16200);

導入庫commons-lang3

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.9</version>
</dependency>

並考慮使用下面的代碼`

public static void main(String[] args) {

    int numberOfElements = RandomUtils.nextInt(0, 100);

    boolean useLetters = RandomUtils.nextBoolean(), //
            useNumbers = RandomUtils.nextBoolean();

    int keyLength = RandomUtils.nextInt(1, 10), //
            valueLength = RandomUtils.nextInt(1, 10);

            Map<String, String> map = generateMap( //
            numberOfElements, //
            useLetters, //
            useNumbers, //
            keyLength, //
            valueLength //
    );

    for (String key : map.keySet()) {
        System.out.println("key = " + key + "; value = " + map.get(key));
    }
}

private static Map<String, String> generateMap( //
        int numberOfElements //
        , boolean useLetters //
        , boolean useNumbers //
        , int keyLength //
        , int valueLength //
) {
    Map<String, String> result = new HashMap<String, String>();
    for (int i = 0; i < numberOfElements; i++) {

        String key = RandomStringUtils.random(keyLength, useLetters, useNumbers);
        String value = RandomStringUtils.random(valueLength, useLetters, useNumbers);

        result.put(key, value);
    }
    return result;
}

`

IntStream

您的問題不清楚數據類型以及 map 條目的值是否應為 null。 我將假設Integer鍵和 null 值的簡單情況。

Stream 填充 map

RandomThreadLocalRandom類現在提供了一個ints方法。 該方法返回一個 stream 數字,特別是一個IntStream

int initialCapacity = 3;  // 16_200 or 64_800 or 259_200.
Map < Integer, UUID > map = new HashMap <>( initialCapacity );
IntStream numbers = ThreadLocalRandom.current().ints( initialCapacity );
numbers.forEach( number -> map.put( number , null ) );  // Auto-boxing wraps the primitive `int` as an `Integer` object.

轉儲到控制台。

System.out.println( map );

跑的時候。

{837992347=null,1744654283=null,-393617722=null}

Stream 實例化一個 map

您甚至可以單行此,要求 stream 生成Map實例,而不是預先初始化它。

我並不是說這更好,但它有點有趣。 我不得不問Produce a Map from an IntStream of keys來學習如何做到這一點。

Map < Integer, UUID > map =
        ThreadLocalRandom
                .current()                                    // Returns a random number generator.
                .ints( 3 )                                    // Produces three random numbers, the limit being the number passed here.
                .boxed()                                      // Invokes auto-boxing to wrap each primitive `int` as an `Integer` object.
                .collect(                                     // Gathers the outputs of this stream into a collection.
                        Collectors.toMap(                     // Returns a `Collector`, a collector that knows how to produce a `java.util.Map` object.
                                Function.identity() ,         // Returns each `Integer` produced by the stream. No further actions needed here, we just want the number.
                                number -> UUID.randomUUID()   // Generate some object to use as the value in each map entry being generated. Not important to this demo.
                        )                                     // Returns a `Collector` used by the `collect` method.  
                );                                            // Returns a populated map.

map.toString(): {1996421820=bbb468b7-f789-44a9-bd74-5c3d060081d0, -717171145=7bd89a89-8b04-4532-82ae-437788378814, 996407145=351f3cdd-6e37-4a09-8644-59d846a815d4}

如果您想選擇實現Map的具體 class ,則這種流實例化映射方法是 go 的錯誤方法。

Java 11 中的地圖實現表,比較它們的特性

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM