How to get a specific item for example you need to get only " Tim "?

import java.util.HashSet; import java.util.Iterator; class IterateHashSet{ public static void main(String[] args) { // Create a HashSet HashSet<String> hset = new HashSet<String>(); //add elements to HashSet hset.add("Chaitanya"); hset.add("Rahul"); hset.add("Tim"); hset.add("Rick"); hset.add("Harry"); Iterator<String> it = hset.iterator(); while(it.hasNext()){ System.out.println(it.next());//Chaitanya Rahul Tim Rick Harry } } } 
  • if the string "Tim" is stored in the Set, and you want to get the string "Tim" - what's the point in the Set? even if there was an opportunity to make set.get("Tim") ? - Grundy
  • And if I do not create a set, I just need to use it, get the value - so it only helps to convert it to a List or another collection? - mtb
  • @mtb, if I understand correctly, you want to check for the presence of an element in the collection (if so change the question), for this you can use the contains method. - Mikhailov Valentine
  • And if the element in a Set is an object, does it need to extract the field value? - mtb
  • "and if the element in a Set is an object" well, then you need to specify the object in question and by what field of the object you will find the desired one. - Mikhailov Valentine

1 answer 1

 hset.stream().filter(data -> Objects.equals(data, "Tim")).findFirst().get() 
  • I also encountered this question ... I understand that before the Stream API, you could write a method to search for this element, which the iterator would use ...? - Oleksiy Morenets
  • @ Olexiy Morenets, why? It is much simpler -> we do the enumeration of the elements of the collection by the cycle -> in the cycle we set the condition for compliance with the required element -> return element; - GenCloud
  • @ GenCloud - I kind of wrote that. The Set loop is an iterator, no? - Olexiy Morenets