I want to get a key and value pair randomly from java map

Asked 2 years ago, Updated 2 years ago, 115 views

I used hash map to interpret English words as key and value, read one line at a time, and saved it I want to print this out randomly, but I don't know what to do.

map random java

2022-09-22 08:06

2 Answers

You can range random objects and add a value


2022-09-22 08:06

You can obtain elements randomly using random classes as shown below.

Map<String, String> wordMapper = Map.of("school", "school", "book", "book", "class", "class");

Object[] keys = wordMapper.keySet();
String randomKey = keys[new Random().nextInt(keys.length)];

wordMapper.get(randomKey);


2022-09-22 08:06

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.