Try an If expression in Java

Preface

This article was impulsively created under the influence of this article. 4-year-old daughter "Daddy, use only const?"

Text

Do you like Java, everyone?

I didn't like it very much until recently, but nowadays I like it a lot.

There are a lot of libraries, modern syntax and syntax sugar.

However, I can't accept that there is no If expression, so I made something like that.

Finished product

public class Iff<T, R> {
  Map<Predicate<T>, Supplier<R>> evaluations = new LinkedHashMap<>();
  private Supplier<R> elsef;

  public Iff(Predicate<T> condition, Supplier<R> then) {
    evaluations.put(condition, then);
  }

  public Iff<T, R> elseIf(Predicate<T> condition, Supplier<R> then) {
    evaluations.put(condition, then);
    return this;
  }

  public Iff<T, R> elsef(Supplier<R> elsef) {
    this.elsef = elsef;
    return this;
  }

  public Optional<R> eval(T target) {
    for (Map.Entry<Predicate<T>, Supplier<R>> entry : this.evaluations.entrySet()) {
      if (entry.getKey().test(target)) {
        var value = entry.getValue().get();
        return Objects.isNull(value) ? Optional.empty() : Optional.of(value);
      }
    }
    if (this.elsef == null) {
      return Optional.empty();
    } else {
      var result = this.elsef.get();
      if (Objects.isNull(result)) {
        return Optional.empty();
      }
      return Optional.of(result);
    }
  }
}

It is a class that takes a T parameter as an argument, checks it, and returns a value of ʻOptional ` (really this is an if expression ...?)

How to use

I wrote a sample as a test.


class IffTest {

  @Test
  public void testIf() {
    //Evaluate a string and return an Integer
    var result = new Iff<String, Integer>((str) -> str.startsWith("hoge"), () -> 100).eval("hogeFuga");
    Assertions.assertEquals(result.get(), 100);
  }

  @Test
  public void testIfElseFirstMatch() {
    //You can add elseIf as many times as you like with the elseIf method.
    var result = new Iff<String, Integer>((str) -> str.startsWith("hoge"), () -> 100)
      .elseIf((str) -> str.startsWith("hogeFuga"), () -> 200)
      .elseIf((str) -> str.startsWith("hoho"), () -> 300)
      .eval("hogeFuga");
    Assertions.assertEquals(result.get(), 100);
  }

  @Test
  public void noMatch() {
    var result = new Iff<String, Integer>((str) -> str.startsWith("hoge"), () -> 100)
      .elseIf((str) -> str.startsWith("hogeFuga"), () -> 200)
      .elseIf((str) -> str.startsWith("hoho"), () -> 300)
      //You can set the behavior in the case of else with the elsef method
      .elsef(() -> 400)
      .eval(UUID.randomUUID().toString());
    Assertions.assertEquals(result.get(), 400);
  }

  @Test
  public void noMatchNotExistsElse() {
    var result = new Iff<String, Integer>((str) -> str.startsWith("hoge"), () -> 100)
      .elseIf((str) -> str.startsWith("hogeFuga"), () -> 200)
      .elseIf((str) -> str.startsWith("hoho"), () -> 300)
      .eval(UUID.randomUUID().toString());
    //If none of the expressions match, Empty will be returned
    result.ifPresentOrElse(v -> {
      Assertions.fail();
    }, () -> {
      //If it is else, the answer is correct
    });
  }

  @Test
  public void elseResultIsNull() {
    var result = new Iff<String, Integer>((str) -> str.startsWith("hoge"), () -> 100)
      .elseIf((str) -> str.startsWith("hogeFuga"), () -> 200)
      .elseIf((str) -> str.startsWith("hoho"), () -> 300)
      .elsef(() -> null)
      .eval(UUID.randomUUID().toString());
    Assertions.assertTrue(result.isEmpty());
  }

  @Test
  public void elseIfResultIsNull() {
    var result = new Iff<String, Integer>((str) -> str.startsWith("hoge"), () -> 100)
      .elseIf((str) -> str.startsWith("mogemoge"), () -> null)
      .elseIf((str) -> str.startsWith("hoho"), () -> 300)
      .elsef(() -> null)
      .eval("mogemoge");
    Assertions.assertTrue(result.isEmpty());
  }
}

Recommended Posts

Try an If expression in Java
Second decoction: Try an If expression in Java
How to solve an Expression Problem in Java
Try using RocksDB in Java
Try calling JavaScript in Java
Try developing Spresense in Java (1)
Try functional type in Java! ①
I sent an email in Java
Try implementing Android Hilt in Java
Try implementing GraphQL server in Java
Try running Selenuim 3.141.59 in eclipse (java)
I made an annotation in Java.
Try running AWS X-Ray in Java
Try to implement Yubaba in Java
Run an external process in Java
Try to solve Project Euler in Java
Try to implement n-ary addition in Java
Try using the Stream API in Java
Map without using an array in java
Try using JSON format API in Java
Try calling the CORBA service in Java 11+
Try making a calculator app in Java
Partization in Java
Changes in Java 11
Rock-paper-scissors in Java
[Java] Lambda expression
I want to ForEach an array with a Lambda expression in Java
Pi in Java
Roughly try Java 9
Java lambda expression
FizzBuzz in Java
I want to send an email in Java.
Try scraping about 30 lines in Java (CSV output)
Try to create a bulletin board in Java
Try using Sourcetrail (win version) in Java code
Try using GCP's Cloud Vision API in Java
Try using the COTOHA API parsing in Java
Try adding text to an image in Scala using the Java standard library
I get an error when I try to use "^" or "$" in ruby ​​regular expression
[java] sort in list
Read JSON in Java
Interpreter implementation in Java
Make Blackjack in Java
Try calling synchronized methods from multiple threads in Java
Rock-paper-scissors app in Java
Constraint programming in Java
Put java8 in centos7
Omission of curly braces in if statement (Java silver)
Combine arrays in Java
"Hello World" in Java
Callable Interface in Java
java learning (conditional expression)
java neutral lambda expression 1
I wrote about Java downcast in an easy-to-understand manner
[java] throw an exception
It's late! Try implementing Android Notification in Java (Beginner)
Comments in Java source
Azure functions in java
Try LetCode in Ruby-TwoSum
Format XML in Java
Simple htmlspecialchars in Java