سؤال

You know, something equivalent to:

<T> T single(List<T> list) {
  assertEquals(1, list.size());
  return list.get(0);
}

Does lambdaj contain something like that?

هل كانت مفيدة؟

المحلول

lambdaj has the selectUnique method that throws an exception if there is more than one item satisfying the condition expressed by the given hamcrest Matcher. Since you don't have any particular condition to be matched, you need a Matcher that always returns true (it doesn't seem to me that hamcrest provides such a Matcher out of the box, but it is trivial to implement it), or maybe you would like to check that the (only) object in the list is at least not null, so you could achieve this result with:

selectUnique(list, Matchers.notNullValue());

نصائح أخرى

Not quite the same thing, but Java has a way to create lists (and other collections) that are guaranteed to have only one element. Take a look at Collections.singleton* methods. Note that these collections are immutable (with entry provided at constructions).

Guava has an Iterables.getFirst() method that does exactly that.

If you can use my xpresso library you can write:

x.list(iterable).toScalar();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top