简体   繁体   中英

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

I would like to create a map that will generate random data( it will generate a random value for each key). The map is meant to take in doubles and this is from an exercise an should be considered an alternative in case i the previous map with the data in the file cannot be used (mapOfEarth) I have thought deeply about it but can't get a right answer. help? I know the sizes for the map but don't know the how to generate the values. I tried the following code:

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

import library commons-lang3

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

and consider using code below `

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

Your Question is unclear about data types and whether the value of the map entries should be null. I will presume the simple case of Integer keys and null values.

Stream populates a map

The Random and ThreadLocalRandom classes now offer an ints method. That method returns a stream of numbers, specifically a 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.

Dump to console.

System.out.println( map );

When run.

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

Stream instantiates a map

You could even make a one-liner of this, asking the stream to produce the Map instance rather than pre-initializing it.

I am not suggesting this is better, but it is a bit interesting. I had to ask Produce a Map from an IntStream of keys to learn how to do this.

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}

This stream-instantiates-map approach is the wrong way to go if you want to choose the concrete class implementing Map .

Java 11 中的地图实现表,比较它们的特性

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM