You need to sign in to do that
Don't have an account?
Dinesh Gupta Kondapalli
Accessing elements from a Set
hi,
As we can access elements from a LIST through an Index, and we can access elements from a MAP through the KEY.. How can we access the elements directly from a SET (apart from iterating it in a loop) ??
As we can access elements from a LIST through an Index, and we can access elements from a MAP through the KEY.. How can we access the elements directly from a SET (apart from iterating it in a loop) ??
Please follow the below code
Please let me know if it helps
Best Regards
Naga Kiran
However we can -
1. check whether a Set already contains a value using 'contains()' method.
2. add a value if it does not already contain that using 'add()' method.
3. remove a value if it already has it using 'remove()' method.
4. remove all values that are present in some other list/set using 'removeAll()' method - Complement from Set theory.
5. add all values that are present in some other list/set using 'addAll()' method - Union from Set theory.
6. retain only the values that are present in some other list/set using 'retainAll()' method - Intersection from Set theory.
If none of the answers helped you significantly but its resolved, please post the solution. You may also mark your solution as the best answer.
But with that code, we can only get the first element of the SET right, what if I want to access an element somewhere at middle. I can't.
1. Set - You can't access elements. Use to check for existence, non-existence or deduplication.
2. Map - You can access any random element in a Map, if you know the key. Use when you want to access elements in a random order.
3. List - You can access an element if you know its index i.e. the order in which it was added the List.
In Naga's code above, you are retrieving a value from List rather than a Set.