문제

Suppose a method returns Iterable<Type>. Is there a more elegant and efficient way to check whether what is returned is empty (or of some given size) than what I'm doing now?

int i = 0;
for (Type dummy : method)
  i++;

if (i == 0)
...
도움이 되었습니까?

해결책

You can check if the an Iterable is empty using iterator().hasNext().

    Iterable<Type> i = /* assigned somehow */;
    i.iterator().hasNext();

다른 팁

You could use Guava's Iterables.isEmpty:

boolean empty = Iterables.isEmpty(method);

To find a size of an Iterable there is also Iterables.size:

int size = Iterables.size(method);

If you have Iterable it provide iterator(). Check hasNext().

And se the javadoc.

Iterator<String> itr = collectionObject.iterator();
while (itr.hasNext()) {
//process here with next method on itr object
}
if (element.equals("")) {
System.out.println("Empty...");
}    
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top