如何创建一个包含随机键和Java值的映射?

问题描述 投票:0回答:2

我想创建一个映射,该映射将生成随机数据(它将为每个键生成一个随机值)。我对此进行了深思,但无法获得正确的答案。救命?我知道地图的大小,但不知道如何生成值。我尝试了以下代码:

 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);
java random maps
2个回答
0
投票

导入库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;
}

`


0
投票

IntStream

© www.soinside.com 2019 - 2024. All rights reserved.