如何使用lambdaj和String.matches方法過濾Collection<String>
。
我是新來的lambdaj和感覺愚蠢的,因爲給出的例子比這更復雜。使用lambdaj和String.matches方法
3
A
回答
1
這可行,但我不高興,它需要這麼多的代碼來取代簡單的循環。 我比「選擇」更喜歡「過濾器」,因爲它使代碼更簡單,並且我認爲更容易閱讀。
public Collection<String> search(String regex) {
List<String> matches = filter(matches(regex), dictionary);
return matches;
}
static class MatchesMatcher extends TypeSafeMatcher<String> {
private String regex;
MatchesMatcher(String regex) {
this.regex = regex;
}
@Override
public boolean matchesSafely(String string) {
return string.matches(regex);
}
public void describeTo(Description description) {
description.appendText("matches " + regex);
}
}
@Factory
public static Matcher<String> matches(String regex) {
return new MatchesMatcher(regex);
}
1
如果要篩選集合,你可以做如下所述:
@Test
public void test() {
Collection<String> collection = new ArrayList<String>();
collection.add("foo");
collection.add("bar");
collection.add("foo");
List<String> filtered = select(collection, having(on(String.class), equalTo("foo")));
assertEquals(2, filtered.size());
}
+0
謝謝...我想我仍然不相信1.語法是如此詳細,2。我必須寫我自己的匹配來引導,因爲似乎是在hamcrest沒有正則表達式匹配。 – wytten 2012-04-06 14:25:07
2
如果有可能使用having(on(...))
結構去做,調用看起來是這樣的:
select(collection, having(on(String.class).matches("f*")))
但不幸的是,這是不可能的,因爲String
類是final的,所以on(String.class)
無法創建having
匹配器所需的代理。
儘管hamcrest不帶正則表達式匹配器,你不必自己寫。該網提供了幾個實現。我希望看到這樣的匹配器在一個隨時可用的公共庫中,我可以簡單地將它包含爲依賴關係,而不必複製源代碼。
相關問題
- 1. 不兼容使用String.matches
- 2. 在lambdaj關閉使用
- 3. 用於java的String.matches方法的正則表達式?
- 4. 與lambdaj
- 5. smartgwt中使用String.matches(正則表達式)
- 6. DOTALL for String.matches()
- 7. string.matches(「。*」)返回false
- 8. 使用Lambdaj排序地圖/ EntrySet
- 9. 在android開發中使用lambdaj庫
- 10. 在String.matches()方法中轉義句號時遇到麻煩
- 11. lambdaj安裝
- 12. LambdaJ for eachach
- 13. GWT的LambdaJ
- 14. Lambdaj類鑄件
- 15. String.matches和Matcher.matches有什麼區別?
- 16. 基於多輸入比較使用hamcrest和lambdaj的對象
- 17. 簡單的選擇方法(lambdaj)得到異常
- 18. lambdaJ和ClassCastException對簡單的選擇
- 19. LambdaJ index()和密鑰類型轉換
- 20. Android上的Lambdaj NoClassDefFoundError
- 21. 使用兩個單獨的過濾標準,使用Lambdaj
- 22. PatternSyntaxException被拋出與String.matches()?
- 23. 避免在Java的string.matches()方法中兩次匹配相同的值
- 24. LambdaJ類屬性匹配器
- 25. 如何在我的應用程序中使用lambdaj
- 26. 使用ContextAttribute和方法
- 27. 使用數組和方法
- 28. 使用getElementsByTagName和getAttribute方法
- 29. 使用$ .getJSON方法和PHP
- 30. 使用string.matches檢查最後一個字符是否爲元音
那麼,它需要很多代碼*一次*。我在單元測試庫中添加了一個正則表達式匹配器,所以我不必再次編寫它。如果我在生產代碼中使用匹配器,我只需將正則表達式匹配器移動到適當的庫。正如我的回答中所指出的那樣,我希望看到這個匹配器在一個隨時可用的公共圖書館中。 – 2012-04-11 19:08:40