Advertisement
Guest User

UTP ćwiczenia

a guest
Nov 12th, 2019
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.31 KB | None | 0 0
  1. package Zad4;
  2.  
  3. import java.util.NoSuchElementException;
  4. import java.util.function.Consumer;
  5. import java.util.function.Function;
  6. import java.util.function.Predicate;
  7.  
  8. public class Maybe<T> {
  9.  
  10.     private T value;
  11.  
  12.     private boolean present;
  13.  
  14.     private Maybe(T value) {
  15.         present = true;
  16.         this.value = value;
  17.     }
  18.  
  19.     private Maybe() {
  20.         present = false;
  21.     }
  22.  
  23.     public static <T> Maybe<T> of(T value) {
  24.         if (value == null)
  25.             return new Maybe<>();
  26.         else
  27.             return new Maybe<>(value);
  28.  
  29.     }
  30.  
  31.     public void ifPresent(Consumer<T> cons) {
  32.         if (present)
  33.             cons.accept(value);
  34.     }
  35.  
  36.  
  37.     public <T, S> Maybe <T> map (Function <T, S> func){
  38.             return Maybe.of(func.apply(value));
  39.     }
  40.  
  41.     public T get (){
  42.         if(present)
  43.             return value;
  44.         else
  45.             throw new NoSuchElementException("maybe is empty");
  46.     }
  47.  
  48.     public boolean isPresent(){
  49.         return present;
  50.     }
  51.  
  52.     public <T> T orElse(T defVal){
  53.         if(present)
  54.             return (T)value;
  55.         else
  56.             return defVal;
  57.     }
  58.  
  59.     public <T> Maybe filter(Predicate<T> pred){
  60.         if(pred.test((T) this.value))
  61.             return this;
  62.         else
  63.             return new Maybe();
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement