Check if only one element exists with Guava

I recently had to make a “special case” scenario if there is only one item in the collection. Testing for ...size() == 1and retrieving with the help ...iterator.next()looked ugly, so I created two methods in the brew Collections home class:

public class Collections {
    public static <T> boolean isSingleValue(Collection<T> values) {
        return values.size() == 1;
    }

    public static <T> T singleValue(Collection<T> values) {
        Assert.isTrue(isSingleValue(values));
        return values.iterator().next();
    }
}

A few days ago, I discovered that Guava has a method called Iterables.getOnlyElement . It covers my need and replaces singleValue, but I cannot find a match for isSingleValue. Is it for design? Should I ask a function request for a method Iterables.isOnlyElement?

EDIT: Since there were a few changes, I decided to open a promotion on guava - question 957 . The final permission is "WontFix". The arguments are very similar to what Thomas / Xaerxess provided.

+5
source share
3 answers

Well, you wouldn’t win much by replacing values.size() == 1with a method, except that you can check for null. However, there are methods for this in Apache Commons Collections (as well as in Guava, I suppose).

I would rather write if( values.size() == 1 )or if( SomeHelper.size(values) == 1 )
, than if( SomeHelper.isSingleValue(values) )- in the first two approaches, the intention is much clearer, and he should write in the same way as in the third approach.

+10
source

( - @daveb, : , Iterables#getOnlyElement IllegalArgumentException NoSuchElementException) - , Iterables.isSingleValue(Iterable).

, . :

  • invokation ( next() , hasNext() )
  • , ( null, Map#get(Object) - , , )

, , ( !), .

, , 1, ( ).
- collection.iterator.next() (NoSuchElementException , ).
, Iterables.getFirst(iterable, default) .

P.S. Collections#isSingleValue (, ), , Iterables#getOnlyValue.

P.P.S. Guava 57 . Java. , , , , ; boolean check , API .

+6

Now I have the same problem.

I will solve with this code:

public static <T> void hasJustOne(T... values) {
    hasJustOne(Predicates.notNull(), values);
}

public static <T> void hasJustOne(Predicate<T> predicate, T... values) {
    Collection<T> filtred = Collections2.filter(Arrays.asList(values),predicate);
    Preconditions.checkArgument(filtred.size() == 1);
}
0
source

All Articles