5

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?

ripper234
  • 222,824
  • 274
  • 634
  • 905
  • 2
    For the uninitiated can you explain what single() operator does in C#? – Pushkar Jan 04 '11 at 18:53
  • 2
    It's an extension method on `IEnumerable` which gets the iterator, ensures that the iterator returns exactly one element and then returns that element to the caller. – CodesInChaos Jan 05 '11 at 10:32
  • @Apache - I did explain - what better way to explain than to provide a code sample? – ripper234 Jan 05 '11 at 12:11

4 Answers4

1

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());
Mario Fusco
  • 13,548
  • 3
  • 28
  • 37
0

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).

Konstantin Komissarchik
  • 28,879
  • 6
  • 61
  • 61
  • I don't want to generate a list, I want to take an existing list, verify it has one element, and get that element. – ripper234 Jan 05 '11 at 12:12
-1

If you can use my xpresso library you can write:

x.list(iterable).toScalar();
aburkov
  • 13
  • 2
  • 5
-2

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

Otavio Macedo
  • 1,542
  • 1
  • 13
  • 34
  • 3
    It seems to me that Iterables.getFirst() doesn't do what asked by the question (throwing an exception if the list has more than one item), but it allows to define a default value if such item doesn't exist. – Mario Fusco Jan 05 '11 at 10:07