2010-11-26 54 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();