在java中是否有和LINQ的Single等價的東西?也許在lambdaj?LINQ's Single in java?
回答
這是一個非常簡單的一個實現自己,說實話:
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;
}
(或者把它放在一個泛型類,而不是使得該方法一般的你可能會決定使用一個不同的異常類型了。 )
不過,我更喜歡@埃米爾的答案,假設番石榴足夠輕。藉助Maven,導入第三方庫非常容易,因此「整合新庫」的障礙降低了。另請參閱http://stackoverflow.com/questions/4263607/what-is-the-de-facto-standard-for-action-func-classes – ripper234 2010-11-26 18:07:20
順便說一句,你在哪裏在過去幾天?我在過去幾天問了大約25個問題,其中有些問題還沒有答案,我相信你知道90%的答案:)幾乎所有的問題都比這個問題更重要... http:// stackoverflow.com/users/11236/ripper234 – ripper234 2010-11-26 18:12:05
@ Jon的解決方案的防禦性較差的版本。
Collection<T> coll;
T first = col.iterator().next();
添加支票以品嚐。
如果你可以用我的xpresso庫,你可以這樣寫:x.list(iterable).toScalar();
- 1. jqGrid:searchrules in single字段搜索
- 2. Linqs是「.Distinct()」隱含
- 3. 唧唧to same more more more single single single single single single single single single single single more more??
- 4. grep for multiple strings in a single line
- 5. class in class in java
- 6. select count(*)and count(*)where column is not null in single query
- 7. Single In House Provisioning Profile - 分發多個iOS應用程序
- 8. Single for-loop進入多列(JAVA)
- 9. int pixels in bmp in java
- 10. Select language in Hypertable in Java
- 11. jaxws multple webservices single wsdl
- 12. CAS Single logout not working
- 13. Single Elimination Tournament算法
- 14. Multiple XSL to single PDF
- 15. Collections.sort()in Java
- 16. PreparedStatement Insert in Java
- 17. AddressBook in Java
- 18. NETWORKDAYS.INTL in Java
- 19. Mergesort in java
- 20. PrintWriter&File in java
- 21. Persistant in Java
- 22. 「object = this」in java
- 23. xmltask in java 1.7?
- 24. Shapiro Wilks in java
- 25. HighScore in java?
- 26. Memcached in java
- 27. this.set(charHere)in JAVA
- 28. IN JAVA PROGRAMMING
- 29. Infiniband in Java
- 30. Wikipedia Api in java
檢查這一項:github.com/nicholas22/jpropel-light,例如:新String(){「james」,「john」,「john」,「eddie」} .where(startsWith(「j」))。toList()。distinct(); – 2011-10-08 10:27:56
jpropel看起來不錯,但我找不到它在maven回購。太糟糕了... – 2012-10-28 12:58:04