gpt4 book ai didi

java - 数组的特定元素匹配多个条件并返回 boolean 值

转载 作者:行者123 更新时间:2023-12-02 01:07:17 32 4
gpt4 key购买 nike

我想要最优化和最简单的方法来在 Java 8 中编写此代码:


(Authentication auth, HttpServletRequest request, ....)

...

Cookie cookies[] = request.getCookies();
if (cookies != null) {

for (Cookie cookie : cookies) {
if (cookie.getName().equals("_id")) {
boolean bool_1 = isIdCookieValid(cookie, auth);
}
else if (cookie.getName().equals("XSRF-TOKEN")) {
boolean bool_2 = isXSRFTokenValid(cookie, request);
}
}

if (bool_1 && bool_2) {
System.out.println("Ok");
}
// else if they are not both true do nothing
}

也许使用 Stream 类?

最佳答案

也许有更简单的方法:

  • 只需更换您的
Cookie cookies[] = request.getCookies();
if (cookies != null) {

for (Cookie cookie : cookies) {
if (cookie.getName().equals("_id")) {
boolean bool_1 = isIdCookieValid(cookie, auth);
}
else if (cookie.getName().equals("XSRF-TOKEN")) {
boolean bool_2 = isXSRFTokenValid(cookie, request);
}
}

if (bool_1 && bool_2) {
System.out.println("Ok");
}
// else if they are not both true do nothing
}
Cookie[] cookies = request.getCookies();
if (cookies != null) {
boolean bool = Arrays.stream(cookies)
.filter(cookie ->
(cookie.getName().equals("_id") ?
isIdCookieValid(cookie, auth) :
cookie.getName().equals("XSRF-TOKEN") &&
isXSRFTokenValid(cookie, request)))
.count() == 2;

System.out.println(bool ? "Ok" : "")
}

关于java - 数组的特定元素匹配多个条件并返回 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59850520/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com