A
A
Alexander Odintsov2015-11-21 19:33:14
Java
Alexander Odintsov, 2015-11-21 19:33:14

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;		
  }

This method does not work, it gives NullPointExeption on the test. Is it possible in principle to return a HashMap in this way? Thanks in advance for any help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey_gr, 2015-11-21
@ShumaHerr

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 question

Ask a Question

731 491 924 answers to any question