Home > Software engineering >  How can I write this simple Java 8 line of code into Java 7
How can I write this simple Java 8 line of code into Java 7

Time:04-19

I'm trying to implement a CSRF token, but all the info is programmed with Java 8 version, so what I need is some help rewriting this line in Java 6/7:

tokenCookie = Arrays.stream(httpReq.getCookies()).filter(c -> c.getName().equals(csrfCookieExpectedName)).findFirst().orElse(null);

Actually from that line I'm only getting the error in:

c -> c.getName().equals(csrfCookieExpectedName)

CodePudding user response:

In addition to @GIO's answer, you could try for-each loop like this:

public Cookie getExpectedCookieName(Cookie[] cookies) {
    for (Cookie c : cookies) {
        if (c.getName().equals(csrfCookiesExpectedName)) {
            return c;
        }
    }
    return null;
}

and call it like this : tokenCookie = getExpectedCookieName(httpReq.getCookies());

CodePudding user response:

This is can be converted using a pretty simple for loop. What you need is basically to check every single element of the array, find the first matching element that you need an exit from the loop, if no element matches then simply return null;

public Cookie getExpectedCookieName() {

   for (int i = 0; i < httpReq.getCookies().length; i  ) {
       if(httpReq.getCookies()[i].getName().equals(csrfCookiesExpectedName)) {
           return httpReq.getCookies()[i];
       }
   }

   return null;
}
  • Related