Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get 100 objects from a Set as a collection?

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?

like image 869
Kamal Kannan Avatar asked Dec 12 '25 15:12

Kamal Kannan


2 Answers

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.

like image 139
Alexis C. Avatar answered Dec 14 '25 05:12

Alexis C.


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.

like image 45
Rahul Avatar answered Dec 14 '25 05:12

Rahul