2010-11-26 51 views
1

在java中是否有和LINQ的Single等价的东西?也许在lambdajLINQ's Single in java?

+1

检查这一项:github.com/nicholas22/jpropel-light,例如:新String(){“james”,“john”,“john”,“eddie”} .where(startsWith(“j”))。toList()。distinct(); – 2011-10-08 10:27:56

+0

jpropel看起来不错,但我找不到它在maven回购。太糟糕了... – 2012-10-28 12:58:04

回答

8

这是一个非常简单的一个实现自己,说实话:

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; 
} 

(或者把它放在一个泛型类,而不是使得该方法一般的你可能会决定使用一个不同的异常类型了。 )

+0

不过,我更喜欢@埃米尔的答案,假设番石榴足够轻。借助Maven,导入第三方库非常容易,因此“整合新库”的障碍降低了。另请参阅http://stackoverflow.com/questions/4263607/what-is-the-de-facto-standard-for-action-func-classes – ripper234 2010-11-26 18:07:20

+0

顺便说一句,你在哪里在过去几天?我在过去几天问了大约25个问题,其中有些问题还没有答案,我相信你知道90%的答案:)几乎所有的问题都比这个问题更重要... http:// stackoverflow.com/users/11236/ripper234 – ripper234 2010-11-26 18:12:05

0

@ Jon的解决方案的防御性较差的版本。

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

添加支票以品尝。

-1

如果你可以用我的xpresso库,你可以这样写:x.list(iterable).toScalar();