1

Is there an equivalent to LINQ's Single in java? Perhaps in lambdaj?

ripper234
  • 222,824
  • 274
  • 634
  • 905
  • 1
    Check this one: github.com/nicholas22/jpropel-light, example:new String[] { "james", "john", "john", "eddie" }.where(startsWith("j")).toList().distinct(); – NT_ Oct 08 '11 at 10:27
  • jpropel seems nice, but I can't find it in maven repo. too bad ... – Jon Martin Solaas Oct 28 '12 at 12:58

4 Answers4

8

It's a pretty easy one to implement yourself, to be honest:

public static <T> T single(Iterable<T> source) {
  Iterator<T> iterator = source.iterator();
  if (!iterator.hasNext()) {
    throw new IllegalArgumentException("No elements");
  }
  T first = iterator.next();
  if (iterator.hasNext()) {
    throw new IllegalArgumentException("More than one element");
  }
  return first;
}

(Or put it in a generic class instead of making the method generic. You may decide to use a different exception type, too.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Still, I prefer @Emil's answer, assuming guava is lightweight enough. With Maven, importing 3rd party libraries is so easy that "integrate a new library" barrier is lowered. See also http://stackoverflow.com/questions/4263607/what-is-the-de-facto-standard-for-action-func-classes – ripper234 Nov 26 '10 at 18:07
  • BTW, where were you in the last few days??? I asked about 25 questions in the last few days, some of them are still unanswered, and I'm sure you know the answers to 90% of them :) Almost all of them more important than this question... http://stackoverflow.com/users/11236/ripper234 – ripper234 Nov 26 '10 at 18:12
  • @ripper234: Oh Guava is a wonderful library, and if you're happy to use an extra library, it's *absolutely* worth having. And looking at the first couple of pages of your questions, they're database-related ones which I wouldn't know :( – Jon Skeet Nov 26 '10 at 18:27
3

Using Guava:

Iterables.getOnlyElement(Iterable< T > iterable)

Emil
  • 13,577
  • 18
  • 69
  • 108
0

A less defensive version of @Jon's solution.

Collection<T> coll;
T first = col.iterator().next();

Add checks to taste.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
-1

If you can use my xpresso library you can write: x.list(iterable).toScalar();

aburkov
  • 13
  • 2
  • 5