java hashmap choosing

yarekGmail used Ask the Experts™
hello experts

public HashMap<String,User> users = new HashMap<String,User>();
public String banned[];

My goal is to RANDOMLY choose 5 users from "users" (all distinct) that are not include in banned[]

Any clues ?

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
First, extract the keys from the map.
Then remove all the keys in banned from the keys you have.
Then shuffle the keys to get them in random order.
Now go over the first five keys (assuming you have that many) and get their matching users.

See code below, hope that's you meant.
Sorry, forgot the code.
List<String> mapKeys = new ArrayList<String>(users.keySet());
		List<String> bannedAsList = Arrays.asList(banned);

		for (int i = 0 ; i < Math.min(mapKeys.size(), 5) ; i++)
			String currentKey = mapKeys.get(i);
			System.out.println("Value is " + users.get(currentKey));

Open in new window

you want to use Random.  It is explained here (no shuffling required):


Excellent work !
works perfectly !

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial