Set s = userIdVsUserInfo.keySet();
As you can see im taking the keySet from a hashmap userIdVsUserInfo and store it in a Set s. Since the construction of the hashmap is dynamic,the keyset may have more than 100 objects.
how can i get 100 objects as a collection?
With java-8, you could get a stream of keys and limit it to get 100 elements.
Set<MyKey> hundredKeys =
map.keySet().stream().limit(100).collect(Collectors.toSet());
I don't know what you mean by doing it without looping, there will always be a kind of iteration behind anyway.
Since HashMap doesn't store the elements in order, the first 100 elements you try to get using the keySet() may not be actually be the first 100 inserted.
Nonetheless, since you want the result as a Collection and without using a loop explicitly, I suppose you can use a List in that case
List<String> list = new ArrayList<>(userIdVsUserInfo.keySet()); // put the elements into a list
list = list.subList(0, 100); // get a subList with 100 elements
And if you're very much concerned about getting a Set of 100 elements, you can create a Set out of the List again, but that's really an overkill.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With