Search code examples
javastringcountmax

Write a program to return the length of the longest word from a string whose length is even?


Optional<Integer> opInt = Arrays.asList(s.split("\\s")).stream()
  .map(l -> l.length())
  .filter(l -> l % 2 == 0)
  .sorted(Comparator.reverseOrder())
  .findFirst();
System.out.println(opInt.get());

Have written code above for that. Can we write concise code for it.


Solution

    1. Instead of using Arrays.asList().stream(), use Arrays.stream(…).

    2. You can use method reference instead of using the lambda. l -> l.length().

    3. You can replace .sorted(Comparator.reverseOrder()) with a .max()

    4. Refactored Code:

      final OptionalInt max = Arrays.stream(s.split(" "))
          .mapToInt(String::length)
          .filter(l -> l % 2 == 0)
          .max();
    
      System.out.println(max.orElse(0));