将代码转换为Lambda函数

时间:2014-11-27 23:24:38

标签: lambda java-8

您好我有以下代码,它从一个HttpURLConnection对象获取cookie。

           for (int i=1; (headerName = connection.getHeaderFieldKey(i))!=null; i++){
                if (headerName.equals("Set-Cookie")){
                    String cookie = connection.getHeaderField(i);
                    cookie = cookie.substring(0, cookie.indexOf(";"));
                    String cookieName = cookie.substring(0, cookie.indexOf("="));
                    String cookieNameFromConfig = TalismaConnector.config.getValue("api.authentication.cookiename");
                    if (cookieName.equals(cookieNameFromConfig)){
                        //the right cookie to get the content from.
                        jsessionID = cookie.substring(cookie.indexOf("=") + 1, cookie.length());
                        OptJsessionID = Optional.ofNullable(jsessionID);
                        break;
                    }
                }
            }

我喜欢用java 8把它写成一个健壮的lambda函数。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

棘手的部分是在null条件下停止,因为Stream不支持停在任意Predicate上。处理此问题的唯一方法是让匹配项和null的两者都向下传递Stream并使用findFirst找到匹配或第一个null

由于我们不希望在所有中间步骤中处理null,因此我们将这些步骤应用于封装匹配项的Optional而不是Stream本身作为Optional如果是空的话,{1}}将无能为力。

String cookieNameFromConfig = TalismaConnector.config.getValue(
                                                     "api.authentication.cookiename");
IntStream.iterate(1, i -> i+1)
.filter(i -> { String k=connection.getHeaderFieldKey(i);
               return k==null || k.equals("Set-Cookie"); })
.mapToObj(i -> Optional.ofNullable(connection.getHeaderField(i))
  .map(cookie   ->cookie.substring(0, cookie.indexOf(";")))
  .filter(cookie->cookie.regionMatches(0,cookieNameFromConfig,0,cookie.indexOf("="))))
.findFirst().get().ifPresent(cookie -> {
        //the right cookie to get the content from.
        jsessionID = cookie.substring(cookie.indexOf("=") + 1, cookie.length());
        OptJsessionID = Optional.of(jsessionID);
});