Answer the question
In order to leave comments, you need to log in
How to return an iterator?
Good afternoon.
The task has a method that must return an Iterator. The method searches the HashMap for the required string.
public Iterator<String> getStringsContaining(String chars) {
Iterator<String> iterator = this.stringSet.iterator();
if((chars!=null)||(chars!=""))
{
HashSet<String> stringSetTemp = new HashSet<String>();
while (iterator.hasNext()) {
if(!iterator.next().contains(chars))
{
stringSetTemp.add(iterator.next());
}
}
iterator = stringSetTemp.iterator();
}
return iterator;
}
Answer the question
In order to leave comments, you need to log in
the iterator gets out, probably because the iterator is empty, add the hasNext check. In
general, I'm not sure that this is a good practice, so I don't know what to return the iterator from. It's better to just return the set.
Well, or if it is possible to use java 8
public Stream<String> filterStringSet(final String filter) {
if (filter == null || filter.isEmpty())
return Stream.empty(); // можно конечно и null вернуть, но тогда это придется обрабатывать
return stringSet.stream()
.filter(str -> str.contains(filter));
}
// ну и потом
filterStringSet("фильтр").forEach(System.out::println)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question