0

Hello I Just started learning Lambda expressions, how do I write this with Lambda expressions?

  public static void greaterThanFive(String str){
    if(str.length() > 5){
        System.out.println("String length is larger than 5 ");
    }else{
        System.err.println("String length less than 5");
    }

if it was just an, if statement I could just do this:

Predicate<String> greaterThanFive = (s)-> s.length() > 5;

But I can't really figure out when it's an if-else statement.

Peter Barnes
  • 79
  • 2
  • 9

2 Answers2

0
Comparator<String> c = (String first, String second) -> {
if (first.length() < second.length()) return -1;
else if (first.length() > second.length()) return 1;
else return 0;
};

I believe this answers your question. For more info, read Java8 for really impatient. Its a really good book.

Prudvinath
  • 15
  • 1
  • 5
  • Hmm is it not possible using filter instead of the if statement? – Peter Barnes May 10 '16 at 20:00
  • I believe filter can only be called on a stream and any intermediate operation on a stream results in another stream. So, we may not achieve the desired outcome you are expecting (This is to my knowledge, I'm also learning java). – Prudvinath May 10 '16 at 20:29
0

Using blocks, you can create lambda expressions that have multiple statements or big statements (like an if-else). Example:

new Thread( () -> { // Btw, you can use java.lang.Runnable with a lambda
    System.out.println("A wild NEW THREAD appeared!"); // :)
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {}
    System.out.println("Enemy NEW THREAD ran away!");
});

This means all you have to do is to enclose that if-else in the block of a lambda:

Consumer<String> greaterThanFive = (s) -> {
    // ...
};

Note that there's a semicolon after the block.

The SE I loved is dead
  • 1,517
  • 4
  • 23
  • 27
  • Are there more convenient Funktional interface than Predicate for this kind of stuff like comparator? – Peter Barnes May 10 '16 at 20:22
  • It depends. Here, you should use a `Consumer` because the method you're trying to convert into a lambda expression returns `void` (I didn't look at the return type before the edit :/). `Predicate` is for converting methods that return a `boolean`. – The SE I loved is dead May 10 '16 at 20:29