How to simplify my code using stream or lambda

String convSummary(String l) {
    String s = l.toLowerCase(), r ="";
    for(int i = 0 ; i < s.length() ;i++){
        char c = s.charAt(i);
        if(c == 'a' || c == 'b' || c == 'c' || c == 'd' || c == 'e')
            r += (char) (c & 0x5f);
        if(c == 'v' || c == 'w' || c == 'x' || c == 'y' || c == 'z')
            r += c;
    }
    return r;
}

How can I simplify my code using stream or lambda? I start, I want to know more about lambda and stream Thanks for helping ...

+4
source share
3 answers

You can use String.chars()to get a stream of characters, but there are more important optimizations here:

  • Not concatenation of string characters by character. Use StringBuilder.
  • Use else ifinstead of two ifwhen conditions are mutually exclusive (a character cwill never be one of "abcde" and "vwxyz" at the same time)
  • If the characters to check are in the ASCII range, use the condition in the range rather than checking the values ​​one at a time

:

String convSummary2(String s) {
    StringBuilder sb = new StringBuilder();
    s.chars().map(Character::toLowerCase).forEach(c -> {
        if ('a' <= c && c <= 'e') {
            sb.append((char)(c & 0x5f));
        } else if ('v' <= c && c <= 'z') {
            sb.append((char) c);
        }
    });
    return sb.toString();
}
+3

, Janos , , , .

, streams/lambdas; if filter, map if, collect .

return
      s.toLowerCase()
       .chars()
       .filter(i -> 'a' <= i && i <= 'e' ||
                    'v' <= i && i <= 'z')
       .map(i -> 'a' <= i && i <= 'e' ?
                  (char)(i & 0x5f) :
                  (char)i)
       .mapToObj(i -> Character.toString((char)i))
       .collect(Collectors.joining());

, parallel().

+2

Use the following code:

int z=(int)c;
  if(z>=97 && z<=101) //these are the ascii value of the letters
  {
    //code for if c is either a,b,c,d,e   
    System.out.println("a,b,c,d,e");
  }
  else if(z>=118 && z<=122){
      //code for if c is either v,w,x,y,z
      System.out.println("v,w,x,y,z");
  }
0
source

Source: https://habr.com/ru/post/1690167/


All Articles