Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to cast Iterator<Object> to a Set<String>, for instance

Casting an Iterator<Object> to a Set<String>

What would be the cleanest/best practice way?

like image 798
Whimusical Avatar asked May 14 '12 10:05

Whimusical


People also ask

Can we iterate set in Java?

Set iterator() method in Java with Examplesutil. Set. iterator() method is used to return an iterator of the same elements as the set. The elements are returned in random order from what present in the set.


2 Answers

public Set<B> getBs(){
    Iterator<A> iterator = myFunc.iterator();
    Set<B> result = new HashSet<B>();
    while (iterator.hasNext()) {
        result.add((B) iterator.next();
    }
    return result;
}

But of course, it will fail if all the As returned by the iterator are not Bs.

If you want to filter the iterator, then use instanceof:

public Set<B> getBs(){
    Iterator<A> iterator = myFunc.iterator();
    Set<B> result = new HashSet<B>();
    while (iterator.hasNext()) {
        A a = iterator.next();
        if (a instanceof B) {
            result.add((B) iterator.next();
        }
    }
    return result;
}

Using Guava, the above can be reduced to

return Sets.newHashSet(Iterators.filter(myFunc.iterator(), B.class));
like image 194
JB Nizet Avatar answered Sep 20 '22 07:09

JB Nizet


I'm still not 100% sure what you want, but check this out and see:

public static void main(String[] args) {
  final Iterator<?> it = Arrays.asList(new Object[] {"a", "b", "c"}).iterator();
  System.out.println(setFromIterator(it));
}

public static Set<String> setFromIterator(Iterator<?> it) {
  final Set<String> s = new HashSet<String>();
  while (it.hasNext()) s.add(it.next().toString());
  return s;
}
like image 45
Marko Topolnik Avatar answered Sep 22 '22 07:09

Marko Topolnik