[英]Using Java Stream in specific case with mapping and filtering response codes
我的問題是關於 JAVA8 的 lambda 和過濾器的使用。 它是通過 Selenium of Java 完成的,用於測試不同的響應代碼。
如何以最大可能的方式使用 Lambda 來使用 Streams 轉換以下函數?
我想重構的代碼如下為 Streams ,Java 8 的 lambda:
for (int i = 0; i < links.size(); i++) {
if (!(links.get(i).getAttribute("href") == null) && !(links.get(i).getAttribute("href").equals(""))) {
// Find HTTP Status-Code
try {
statusCode = getResponseCode(links.get(i).getAttribute("href").trim());
} catch (IOException e) {
e.printStackTrace();
}
// Check broken link
if (statusCode== 404) {
System.out.println("Broken of Link# "+i+" "+links.get(i).getAttribute("href"));
}
else if (statusCode== 400) {
System.out.println("Bad Request# "+i+" "+links.get(i).getAttribute("href"));
}
else if (statusCode== 401) {
System.out.println("Unauthorized# "+i+" "+links.get(i).getAttribute("href"));
}
else if (statusCode== 403) {
System.out.println("Forbidden# "+i+" "+links.get(i).getAttribute("href"));
}
else if (statusCode== 500) {
System.out.println("Internal server error# "+i+" "+links.get(i).getAttribute("href"));
}
}
}
我現在所擁有的是:
List<AbstractMap.SimpleImmutableEntry<String,Integer>> variablename =
links.stream().map(WebElement::getAttribute("href"));
我試圖做一些事情,過濾掉不是 500,403,401,400,404 的所有內容,只保留映射或一對類似(linkString,responseCode),但我在如何正確地使用它時遇到了一些麻煩拉姆達?
EDIT1:我並不打算通過流放置所有內容,只是為了在此示例中盡可能多地使用它
如果你一塊一塊地拿它是相當簡單的,所以:
// create a set of codes you want to include
Set<Integer> acceptableCodes = new HashSet<>(Arrays.asList(404, 400, 401, 403, 500));
// for (int i = 0; i < links.size(); i++) {
links.stream()
// convert to the href value as that's all we need later on
.map(link -> link.getAttribute("href"))
// filter out anything without a href
// if (!(links.get(i).getAttribute("href") == null) && !(links.get(i).getAttribute("href").equals(""))) {
.filter(href -> href != null)
.filter(href -> !href.equals(""))
// filter out non-matching status codes
.filter(href -> acceptableCodes.contains(getResponseCode(href))
.map(link -> new LinkWithCode(href , getResponseCode(href))
.collect(toList());
把它放在一起,不加注釋,這樣你就可以更容易閱讀:
Set<Integer> acceptableCodes = new HashSet<>(Arrays.asList(404, 400, 401, 403, 500));
links.stream()
.map(link -> link.getAttribute("href"))
.filter(href -> href != null)
.filter(href -> !href.equals(""))
.filter(href -> acceptableCodes.contains(getResponseCode(href))
.map(link -> new LinkWithCode(href , getResponseCode(href))
.collect(toList());
LinkWithCode
是您需要創建的一個類來保存鏈接和狀態代碼。 這假設getResponseCode
不是重量級操作,因為它發生了兩次。
警告:我尚未對此進行測試或將其放入 IDE 中,因此您可能需要進行一些整理工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.