Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

collections - Is there a way to get the value of a HashMap randomly in Java?

Is there a way to get the value of a HashMap randomly in Java?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This works:

Random generator = new Random();
Object[] values = myHashMap.values().toArray();
Object randomValue = values[generator.nextInt(values.length)];

If you want the random value to be a type other than an Object simply add a cast to the last line. So if myHashMap was declared as:

Map<Integer,String> myHashMap = new HashMap<Integer,String>();

The last line can be:

String randomValue = (String) values[generator.nextInt(value.length)];

The below doesn't work, Set.toArray() always returns an array of Objects, which can't be coerced into an array of Map.Entry.

Random generator = new Random();
Map.Entry[] entries = myHashMap.entrySet().toArray();
randomValue = entries[generator.nextInt(entries.length)].getValue();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...