Advertisement
Guest User

Untitled

a guest
Jul 1st, 2014
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 55.83 KB | None | 0 0
  1.  
  2. package testproject8;
  3.  
  4. import java.io.IOException;
  5. import java.io.InvalidObjectException;
  6. import java.io.ObjectInputStream;
  7. import java.io.Serializable;
  8. import java.io.UncheckedIOException;
  9. import java.lang.annotation.ElementType;
  10. import java.lang.annotation.Retention;
  11. import java.lang.annotation.RetentionPolicy;
  12. import java.lang.annotation.Target;
  13. import java.math.BigDecimal;
  14. import java.math.MathContext;
  15. import java.math.RoundingMode;
  16. import java.nio.ByteBuffer;
  17. import java.nio.file.Files;
  18. import java.nio.file.Path;
  19. import java.time.LocalTime;
  20. import java.util.ArrayList;
  21. import java.util.Arrays;
  22. import java.util.Collection;
  23. import java.util.Collections;
  24. import java.util.Comparator;
  25. import java.util.EnumMap;
  26. import java.util.HashMap;
  27. import java.util.HashSet;
  28. import java.util.Iterator;
  29. import java.util.LinkedList;
  30. import java.util.List;
  31. import java.util.Map;
  32. import java.util.Objects;
  33. import java.util.Optional;
  34. import java.util.OptionalDouble;
  35. import java.util.PriorityQueue;
  36. import java.util.Random;
  37. import java.util.RandomAccess;
  38. import java.util.Set;
  39. import java.util.Spliterator;
  40. import java.util.Spliterators;
  41. import java.util.concurrent.Callable;
  42. import java.util.concurrent.atomic.AtomicInteger;
  43. import java.util.function.BiConsumer;
  44. import java.util.function.BiFunction;
  45. import java.util.function.Consumer;
  46. import java.util.function.DoubleBinaryOperator;
  47. import java.util.function.Function;
  48. import java.util.function.IntBinaryOperator;
  49. import java.util.function.IntConsumer;
  50. import java.util.function.IntFunction;
  51. import java.util.function.IntUnaryOperator;
  52. import java.util.function.Predicate;
  53. import java.util.function.Supplier;
  54. import java.util.regex.Pattern;
  55. import java.util.stream.Collector;
  56. import java.util.stream.Collectors;
  57. import java.util.stream.IntStream;
  58. import java.util.stream.Stream;
  59. import java.util.stream.StreamSupport;
  60. import javafx.scene.control.TableCell;
  61. import javafx.scene.control.TableColumn;
  62. import javafx.util.Callback;
  63. import testproject8.package1.MyEnum;
  64.  
  65. /**
  66.  *
  67.  * @author Beheerder
  68.  */
  69. public class TestProject8 {    
  70.     private Map<Class<?>, Object> values;
  71.    
  72.     private void init() {
  73.         String strinzzz = "afdgdfdds";
  74.         strinzzz.substring(5);
  75.        
  76.         PriorityQueue<String> pqs = new PriorityQueue<>();
  77.         LinkedList<Integer> ll = new LinkedList<>();
  78.        
  79.         Set<String> ssere = new HashSet<>();
  80.        
  81.         Stream<String> streamString = Stream.of("a", "b", "c");
  82.         String[] stringArray = streamString.toArray(String[]::new);
  83.         Arrays.stream(stringArray).forEach(System.out::println);
  84.        
  85.         Map<String, String> map = Stream.of("A,1,!","B,2,@","C,3,#","D,4,$","E,5,%")
  86.                 .map(line -> line.split(","))
  87.                 .collect(Collectors.toMap(
  88.                         array -> array[0],
  89.                         array -> array[1]
  90.                 ));
  91.         map.forEach((k, v) -> System.out.println("Key = " + k + " / Value = " + v));
  92.        
  93.         Set<Notifiable> set = new HashSet<>();
  94.         set.add(new NotifiableImpl1());
  95.         set.add(new NotifiableImpl2());
  96.         set.add(new NotifiableImpl3());
  97.  
  98.         Set<? extends Notifiable> set3 = set;
  99.  
  100.         Set<? extends Notifiable> set2 = new HashSet<>();
  101.     //    set2.add(new NotifiableImpl1());
  102.     //    set2.add(new NotifiableImpl2());
  103.     //    set2.add(new NotifiableImpl3());
  104.    
  105.         String input = "abcdd";
  106.         long count = input.chars()
  107.                 .distinct()
  108.                 .count();
  109.         System.out.println(count);
  110.        
  111.         AtomicInteger integer = new AtomicInteger(0);
  112.         IntStream.range(0, 1000000)
  113.                 .parallel()
  114.                 .forEach(i -> integer.getAndIncrement());
  115.         System.out.println(integer.get());
  116.        
  117.         Callback<TableColumn<Factura, BigDecimal>, TableCell<Factura, BigDecimal>> moneyCellFactoryOld =
  118.                     new Callback<TableColumn<Factura, BigDecimal>, TableCell<Factura, BigDecimal>>() {
  119.                         public TableCell call(TableColumn p) {
  120.                             return new MoneyFormatCell();
  121.                         }
  122.                     };
  123.         Callback<TableColumn<Factura, BigDecimal>, TableCell<Factura, BigDecimal>> moneyCellFactory = column -> new MoneyFormatCell();
  124.        
  125.         List<Employee> employeeList = new ArrayList<>();
  126. //        employeeList.sort(Comparator.comparingInt(Employee::getEmpSalary).reversed());
  127.         employeeList.sort(
  128.                 Comparator.comparing(Employee::getEmpName)
  129.                 .thenComparingInt(Employee::getEmpSalary)
  130.         );
  131.        
  132.         List<String> list = Collections.nCopies(6, "abc");
  133.         list.forEach(System.out::println);
  134.        
  135.         long a = 0L;
  136.         if (a > Integer.MAX_VALUE) {
  137.            
  138.         }
  139.        
  140.         Stream<Class<?>> stream = Stream.of(NotifiableImpl1.class, NotifiableImpl2.class, NotifiableImpl3.class);
  141.         HashMap<Class<?>, List<Class<?>>> hashMap = stream
  142.                 .collect(Collectors.groupingBy(
  143.                         Class::getSuperclass,
  144.                         HashMap::new,
  145.                         Collectors.toList()
  146.                 ));
  147.         hashMap.forEach((k, v) -> System.out.println("Key = " + k + " / Value = " + v));
  148.        
  149.         SubClass sub = new SubClass(5);
  150.        
  151.         UnrelatedInterfaceDefault unrelated = new UnrelatedClass();
  152.         unrelated.unrelate();
  153.        
  154.         List<BigDecimal> bdList = new ArrayList<>();
  155.         BigDecimal result2 = bdList.stream()
  156.                 .reduce(BigDecimal.ZERO, BigDecimal::add);
  157. //        
  158. //        List<Invoice> invoiceList = new ArrayList<>();
  159. //        //populate
  160. //        Function<Invoice, BigDecimal> totalMapper = invoice -> invoice.getUnit_price().multiply(invoice.getQuantity());
  161. //        BigDecimal result = invoiceList.stream()
  162. //                .map(totalMapper)
  163. //                .reduce(BigDecimal.ZERO, BigDecimal::add);
  164.        
  165.         List<Invoice> invoiceList = new ArrayList<>();
  166.         //populate
  167.         BigDecimal result = invoiceList.stream()
  168.                 .map(Invoice::total)
  169.                 .reduce(BigDecimal.ZERO, BigDecimal::add);
  170.        
  171.         List<Person> personList = new ArrayList<>();
  172.         personList.add(new Person("Shannon", "Goldstein"));
  173.         personList.add(new Person("Donnie", "Denney"));
  174.         personList.add(new Person("Mark", "Thomas"));
  175.         personList.add(new Person("Julia", "Thomas"));
  176.         Map<String, List<Person>> personMapping = personList.stream()
  177.                 .collect(Collectors.groupingBy(Person::getLastName));
  178.         System.out.println("personMapping = " + personMapping);
  179.        
  180. //        List<String> listString = new ArrayList<>();
  181. //        for (String str : listString) {
  182. //            if (str.charAt(0) == ' ') {
  183. //                // do something with str
  184. //            }
  185. //        }
  186.        
  187.         List<String> listString = new ArrayList<>();
  188.         List<String> filteredString = listString.stream()
  189.                 .filter(s -> s.charAt(0) == ' ')
  190.                 .collect(Collectors.toList());
  191.        
  192.         List<String> stringList = new ArrayList<>();
  193.         stringList.add("a");
  194.         stringList.add("hg");
  195.         stringList.add("dsl");
  196.         stringList.add("sldi");
  197.         stringList.add("ilsdo");
  198.         stringList.add("jlieio");
  199.         Predicate<String> predicate = str -> (str.length() >= 3);
  200.         Map<Boolean, List<String>> mapping = stringList.stream()
  201.                 .collect(Collectors.partitioningBy(predicate));
  202.        
  203.         List<Integer> testList = new ArrayList<>();
  204.         IntStream.rangeClosed(0, 10)
  205.                 .forEach(testList::add);
  206.         testList.forEach(System.out::println);
  207.        
  208.         LinkedList<User> users = new LinkedList<>();
  209.         users.add(new User(1, "User1"));
  210.         users.add(new User(2, "User2"));
  211.         users.add(new User(3, "User3"));
  212.         List<User> resultUserList = users.stream()
  213.                 .filter(user -> user.getId() == 1)
  214.                 .collect(Collectors.toList());
  215.         if (resultUserList.size() != 1) {
  216.             throw new IllegalStateException();
  217.         }
  218.         User resultUser = resultUserList.get(0);
  219.         System.out.println("resultUser = " + resultUser);
  220.        
  221.         User resultTwoUser = users.stream()
  222.                 .filter(user -> user.getId() > 2)
  223.                 .collect(singletonCollector());
  224.         System.out.println("resultTwoUser = " + resultTwoUser);
  225.        
  226. //        Integer[] integerArray = new Integer[1024];
  227. //        int[] intArray = new int[1024];
  228. //        Arrays.setAll(intArray, i -> integerArray[i]);
  229.        
  230. //        int t = 1024;
  231. //        Player[] p = new Player[t];
  232. //        Arrays.sort(p, Comparator.comparingInt(Player::getNumber));
  233.        
  234.         boolean checkOne = containsAllChars("helloworld", "asdfuvjerhelloworld");
  235.         System.out.println("checkOne = " + checkOne);
  236.        
  237.         boolean checkTwo = containsAllChars("helloworld", "lshewodxzr");
  238.         System.out.println("checkTwo = " + checkTwo);
  239.        
  240.         boolean checkThree = containsAllChars("helloworld", "abc");
  241.         System.out.println("checkThree = " + checkThree);
  242.        
  243.         List<String> listOfStrings = new ArrayList<>();
  244.         listOfStrings.add("christopher hitchens");
  245.         listOfStrings.add("william craig");
  246.         listOfStrings.forEach(this::mapper);
  247.        
  248.         CustomList<String> cstmLst = new CustomList<>();
  249.         cstmLst.add("a");
  250.         cstmLst.add("b");
  251.         Collections.sort(cstmLst);
  252.        
  253.         init2();
  254.     }
  255.    
  256.     private void init2() {
  257.         List<Callable<Double>> list = IntStream.range(1, 99)
  258.                 .<Callable<Double>>mapToObj(value -> (() -> calculateResult(value)))
  259.                 .collect(Collectors.toList());
  260. //        
  261. //        List<Callable> list2 = IntStream.range(1, 99)
  262. //                .mapToObj(value -> (() -> calculateResult(value)))
  263. //        
  264. //        IntStream.range(1, 99)
  265. //                .mapToObj(value -> (() -> calculateResult(value)));
  266.        
  267.         init3();
  268.     }
  269.    
  270.     private void init3() {
  271. //        String result = Stream.of("a", "b", "c", "de", "fg", "hij")
  272. //                .map(this::resolve)
  273. //                .flatMap(CustomOptionalOld::flatStream)
  274. //                .findFirst()
  275. //                .get();
  276.        
  277. //        String result = Stream.of("a", "b", "c", "de", "fg", "hij")
  278. //                .map(this::resolve)
  279. //                .map(CustomOptionalOld::getTOrNull)
  280. //                .findFirst()
  281. //                .get();
  282.        
  283.         init4();
  284.     }
  285.    
  286.     private void init4() {
  287.         Collection<String> input = Arrays.asList("1", "2", "3");
  288.         Function<String, String> mapper = x -> x + " " + x;
  289.         Predicate<String> filter = y -> !y.startsWith("1");
  290.         Collector<String, ?, List<String>> toList = Collectors.toList();
  291.  
  292.         List<String> list = ((Supplier<List<String>>)toList.supplier()).get();
  293.         for (String in : input) {
  294.             in = mapper.apply(in);
  295.             if (filter.test(in)) {
  296.                 ((BiConsumer<List<String>, String>)toList.accumulator()).accept(list, in);
  297.             }
  298.         }
  299.        
  300.         System.out.println("list = " + list);
  301.        
  302.         init5();
  303.     }
  304.    
  305.     private void init5() {
  306.         Stream<Integer> stream1 = null;
  307.         Stream<Integer> stream2 = null;
  308.         Integer element = null;
  309.  
  310. //        Stream<Integer> resultStream = Stream.concat(stream1, Stream.concat(stream2, Stream.of(element)))
  311. //                .filter(x -> x != 0)
  312. //                .filter(x -> x != 1)
  313. //                .filter(x -> x != 2);
  314.  
  315. //        Stream<Integer> resultStream = Stream.concat(
  316. //                        stream1,
  317. //                        stream2,
  318. //                        Stream.of(element)
  319. //                )
  320. //                .filter(x -> x != 0)
  321. //                .filter(x -> x != 1)
  322. //                .filter(x -> x != 2);
  323.        
  324.         init6();
  325.     }
  326.    
  327.     private void init6() {
  328.         int[] array = new int[1024];
  329.         //fill
  330.         int[] arrayWithoutDuplicates = Arrays.stream(array)
  331.                 .distinct()
  332.                 .toArray();
  333.        
  334.         fakingRandomAccess();
  335.         init7();
  336.     }
  337.    
  338. //    private void init7() {
  339. //        IntStream tstream = IntStream.rangeClosed(1, 100000000);
  340. //        Collector<Object, ?, Map<Object, List<Object>>> collector = Collectors.groupingBy(i -> Thread.currentThread());
  341. //        Map<Object, List<Object>> coll = tstream.boxed().parallel().collect(collector);
  342. //        coll.replaceAll((thread, list) -> Arrays.asList(list.size()));
  343. //        System.out.println(coll.size() + " threads was used: " + coll);
  344. //    }
  345.    
  346. //    private void init7() {
  347. //        for (int i = 0; i < 2; i++) {
  348. //            try (Scanner scanner = new Scanner(System.in)) {
  349. //                while (scanner.hasNextInt()) {
  350. //                    int next = scanner.nextInt();
  351. //                    if (next == 0) {
  352. //                        break;
  353. //                    }
  354. //                    System.out.println("Input was: " + next);
  355. //                }
  356. //            }
  357. //        }
  358. //    }
  359.    
  360. //    private void init7() {
  361. //        try {
  362. //            long size = Files.walk(Paths.get("C://"))
  363. //                    .parallel()
  364. //                    .peek(System.out::println)
  365. //                    .mapToLong(this::fileSize)
  366. //                    .sum();
  367. //            System.out.println("size = " + size);
  368. //        } catch (IOException ex) {
  369. //            Logger.getLogger(TestProject8.class.getName()).log(Level.SEVERE, null, ex);
  370. //        }
  371. //    }
  372.  
  373.     private long fileSize(final Path path) {
  374.         try {
  375.             return Files.size(path);
  376.         } catch (IOException | UncheckedIOException ex) {
  377.             return 0;
  378.         }
  379.     }
  380.    
  381. //    private <E> void takeList(List<E> list) {
  382. //        
  383. //    }
  384.    
  385. //    private <E> void takeList(ArrayList<E> list) {
  386. //        
  387. //    }
  388.    
  389.     private <E, T extends List<E> & RandomAccess> void takeList(T list) {
  390.        
  391.     }
  392.    
  393.     private void fakingRandomAccess() {
  394. //        List<Integer> linkedList = new LinkedList<>();
  395. //        takeList((List<Integer> & RandomAccess)linkedList);
  396.        
  397. //        List<Integer> linkedList = (List<Integer> & RandomAccess)new LinkedList<Integer>();
  398. //        takeList(linkedList);
  399.     }
  400.    
  401.     private void init7() {
  402.         IntStream.range(0, 100)
  403.                 .boxed()
  404.                 .collect(topPercentFromRangeCollector(Comparator.comparingInt(i -> i), 0.1d, 0.3d))
  405.                 .forEach(System.out::println);
  406.         init8();
  407.     }
  408.    
  409.     private <T> Collector<T, ?, Stream<T>> topPercentFromRangeCollector(Comparator<T> comparator, double from, double to) {
  410.         return Collectors.collectingAndThen(
  411.             Collectors.toList(),
  412.             list -> list.stream()
  413.                 .sorted(comparator)
  414.                 .skip((long)(list.size() * from))
  415.                 .limit((long)(list.size() * (to - from)))
  416.         );
  417.     }
  418.    
  419.     private <T> CustomOptionalOld<T> resolve(final T input) {
  420.         if (new Random().nextBoolean()) {
  421.             return CustomOptionalOld.ofNullable(input);
  422.         }
  423.         return CustomOptionalOld.empty();
  424.     }
  425.    
  426.     private String mapper(final String input) {
  427.         String[] parts = input.split(" ");
  428.         return parts[1] + ", " + parts[0];
  429.     }
  430.    
  431.     public double calculateResult(int value) {
  432.         return 0.0d;
  433.     }
  434.  
  435.     /**
  436.      * @param args the command line arguments
  437.      */
  438.     public static void main(String[] args) {
  439.         new TestProject8().init();
  440.     }
  441.    
  442.     public static long countUniqueCharacters(String input) {
  443.         return input.chars()
  444.                 .distinct()
  445.                 .count();
  446.     }
  447.    
  448.     public static <T> Collector<T, ?, T> singletonCollector() {
  449.         return Collectors.collectingAndThen(
  450.                 Collectors.toList(),
  451.                 list -> {
  452.                     if (list.size() != 1) {
  453.                         throw new IllegalStateException();
  454.                     }
  455.                     return list.get(0);
  456.                 }
  457.         );
  458.     }
  459.    
  460.     public boolean check(final String firstString, final String secondString) {
  461.         //Create a map mapping all characters from the firstString to true/false
  462.         Map<Character, Boolean> map = IntStream.rangeClosed('a', 'z')
  463.                 .boxed()
  464.                 .collect(Collectors.toMap(
  465.                         i -> (char)(int)i,
  466.                         i -> firstString.chars().anyMatch(j -> j == i)
  467.                 ));
  468.        
  469.         return map.entrySet().stream()
  470.                 .filter(entry -> entry.getValue() == true)
  471.                 .map(Map.Entry::getKey)
  472.                 .allMatch(ch -> secondString.chars().anyMatch(i -> i == ch));
  473.     }
  474.    
  475.     public boolean containsAllChars(String a, String b) {
  476.         List<Character> aChars = stringToCharacterList(a);
  477.         List<Character> bChars = stringToCharacterList(b);
  478.         return bChars.containsAll(aChars);
  479.     }
  480.    
  481.     public List<Character> stringToCharacterList(String input) {
  482.         return input.chars().distinct()
  483.                 .mapToObj(i -> (char)i)
  484.                 .collect(Collectors.toList());
  485.     }
  486.    
  487.     public <T, U, R> Collection<R> singleCollectionOf(final Collection<T> collectionA, final Collection<U> collectionB, final Supplier<Collection<R>> supplier, final BiFunction<T, U, R> mapper) {
  488.         if (Objects.requireNonNull(collectionA).size() != Objects.requireNonNull(collectionB).size()) {
  489.             throw new IllegalArgumentException();
  490.         }
  491.         Objects.requireNonNull(supplier);
  492.         Objects.requireNonNull(mapper);
  493.         Iterator<T> iteratorA = collectionA.iterator();
  494.         Iterator<U> iteratorB = collectionB.iterator();
  495.         Collection<R> returnCollection = supplier.get();
  496.         while (iteratorA.hasNext() && iteratorB.hasNext()) {
  497.             returnCollection.add(mapper.apply(iteratorA.next(), iteratorB.next()));
  498.         }
  499.         return returnCollection;
  500.     }
  501.    
  502.     private void init8() {
  503.         List<Integer> list1 = IntStream.range(0, 10).boxed().collect(Collectors.toList());
  504.         List<Integer> list2 = IntStream.range(0, 10).map(n -> n * n + 1).boxed().collect(Collectors.toList());
  505.         singleCollectionOf(list1, list2, ArrayList::new, Pair::new).stream().forEach(System.out::println);
  506.         init9();
  507.     }
  508.    
  509.     private void init9() {
  510.         values = new HashMap<>();
  511.         values.put(Pet.class, new Pet());
  512.         values.put(Car.class, new Car());
  513.        
  514.         System.out.println("get(Pet.class).getClass() = " + get(Pet.class).getClass());
  515.         System.out.println("get(Car.class).getClass() = " + get(Car.class).getClass());
  516.         init10();
  517.     }
  518.    
  519.     @SuppressWarnings("unchecked")
  520.     private <T> T get(Class<T> clazz) {
  521.         return (T)values.get(clazz);
  522.     }
  523.    
  524.     private void init10() {
  525.         System.out.println("ContentType.values(SubType.MAIL) = " + ContentType.values(SubType.MAIL));
  526.         System.out.println("ContentType.values(SubType.DEFAULT) = " + ContentType.values(SubType.DEFAULT));
  527.         init11();
  528.     }
  529.    
  530.     private void init11() {
  531.         IntFunction<String[]> intFunction = String[]::new;
  532.         Function<Integer, String[]> intFunctionBoxed = String[]::new;
  533.         Function<String[], String[]> cloner = String[]::clone;
  534.         String[] s = {};
  535.         init12();
  536.     }
  537.    
  538.     private void init12() {
  539.         Map<String, Integer> map = new HashMap<>();
  540.         map.put("test", 5);
  541.         Map<String, String> mapped = map.entrySet().stream()
  542.                 .collect(Collectors.toMap(Map.Entry::getKey, entry -> String.valueOf(entry.getValue())));
  543.         mapped.forEach((k, v) -> System.out.println("key: " + k + " / value: " + v));
  544.         init13();
  545.     }
  546.    
  547.     private void init13() {
  548.         List<String[]> phrases = Arrays.asList(new String[]{"a", "b", "c"}, new String[]{"a", "a", "b", "d"});
  549.         List<Map.Entry<String, Long>> topEntries = getTopWords(2, phrases.stream().flatMap(Arrays::stream))
  550.                 .collect(Collectors.toList());
  551.         int counter = 1;
  552.         for (Map.Entry<String, Long> entry : topEntries) {
  553.             System.out.println(counter + ": " + entry.getKey() + " - " + entry.getValue());
  554.             counter++;
  555.         }
  556.         init14();
  557.     }
  558.    
  559.     public static Stream<Map.Entry<String, Long>> getTopWords(final int topX, final Stream<String> words) {
  560.         if (topX < 1) {
  561.             throw new IllegalArgumentException("invalid value for topX: " + topX);
  562.         }
  563.         Objects.requireNonNull(words);
  564.         Comparator<Map.Entry<String, Long>> comparator = Comparator.comparingLong(Map.Entry::getValue);
  565.         return words.collect(Collectors.groupingBy(i -> i, Collectors.counting()))
  566.                 .entrySet().stream()
  567.                 .sorted(comparator.reversed())
  568.                 .limit(topX);
  569.     }
  570.    
  571.     private void init14() {
  572.         LinkedList<Integer> linkedList = new LinkedList<>();
  573.         linkedList.add(5);
  574.         linkedList.add(10);
  575.         linkedList.add(15);
  576.         LinkedList<String> resultList = transform(linkedList, i -> (i + 1) + "-" + i);
  577. //        LinkedList<String> resultList = transform(linkedList, i -> (i + 1) + "-" + i, LinkedList::new);
  578.         resultList.forEach(System.out::println);
  579.         init15();
  580.     }
  581.    
  582.     public static <E, R, C extends Collection<? extends R>> C transform(final Collection<E> collection, final Function<? super E, ? extends R> mapper) {
  583.         try {
  584.             Objects.requireNonNull(collection);
  585.             Objects.requireNonNull(mapper);
  586.             Class<? extends Collection> clazz = collection.getClass();
  587.             @SuppressWarnings("unchecked") Collection<Object> returnCollection = clazz.newInstance();
  588.             collection.stream().map(mapper).forEach(returnCollection::add);
  589.             @SuppressWarnings("unchecked") C genericReturnCollection = (C)returnCollection;
  590.             return genericReturnCollection;
  591.         } catch (InstantiationException | IllegalAccessException ex) {
  592.             throw new RuntimeException(ex);
  593.         }
  594.     }
  595.    
  596.     public static <E, R, C extends Collection<R>> C transform(final Collection<E> collection, final Function<? super E, ? extends R> mapper, final Supplier<C> collectionSupplier) {
  597.         Objects.requireNonNull(collection);
  598.         Objects.requireNonNull(mapper);
  599.         Objects.requireNonNull(collectionSupplier);
  600.         return collection.stream().map(mapper).collect(Collectors.toCollection(collectionSupplier));
  601.     }
  602.    
  603.     private void init15() {
  604.         Stream<Integer> stream = IntStream.iterate(0, i -> i + LocalTime.now().getSecond()).skip(1).limit(10).boxed();
  605.         for (int i : iterable(stream)) {
  606.             System.out.println("i = " + i);
  607.         }
  608.         init16();
  609.     }
  610.    
  611.     private static <T> Iterable<T> iterable(final Stream<T> stream) {
  612.         return stream::iterator;
  613.     }
  614.    
  615.     private void init16() {
  616.         String dashes = Stream.generate(() -> "-").limit(80).reduce("", (s1, s2) -> s1 + s2);
  617.         System.out.println(dashes);
  618.         init17();
  619.     }
  620.    
  621.     private void init17() {
  622.         String[] stringArray = new String[]{
  623.             "a",
  624.             "bc",
  625.             "def",
  626.             "ghij"
  627.         };
  628.        
  629.         Arrays.sort(stringArray, new Comparator<String>() {
  630.             @Override
  631.             public int compare(String s1, String s2) {
  632.                 return s1.length() - s2.length();
  633.             }
  634.         });
  635.         Arrays.stream(stringArray).forEach(System.out::println);
  636.        
  637.         Arrays.sort(stringArray, (s1, s2) -> s1.length() - s2.length());
  638.         Arrays.stream(stringArray).forEach(System.out::println);
  639.        
  640.         Arrays.sort(stringArray, Comparator.comparingInt(String::length));
  641.         Arrays.stream(stringArray).forEach(System.out::println);
  642.         init18();
  643.     }
  644.    
  645.     private void init18() {
  646.         Arrays.stream(Operation.values())
  647.                 .forEach(op -> System.out.println("Performing operation " + op.getSymbol() + " on 2 and 4: " + op.applyAsDouble(2, 4)));
  648.         init19();
  649.     }
  650.    
  651.     private void init19() {
  652.         OptionalDouble d1 = OptionalDouble.of(1.);
  653.         OptionalDouble d2 = OptionalDouble.of(2.);
  654.         OptionalDouble d3 = OptionalDouble.of(3.);
  655.  
  656.         OptionalDouble result = OptionalDoubleImproved.of(d1)
  657.                 .applyFunction((a, b) -> a + b, d2)
  658.                 .applyFunction((a, b) -> a * b, d3)
  659.                 .get();
  660.         System.out.println("result = " + result);
  661.         init20();
  662.     }
  663.    
  664.     private void init20() {
  665.         List<String> languages = Arrays.asList("c#", "java", "python", "scala");
  666.         Pattern pattern = Pattern.compile("[a-z]{4}");
  667.         languages.stream()
  668. //                .filter(str -> pattern.matcher(str).matches())
  669.                 .filter(pattern.asPredicate())
  670.                 .forEach(System.out::println);
  671.         init21();
  672.     }
  673.    
  674.     private void init21() {
  675.         Stream<Integer> stream1 = IntStream.rangeClosed(0, 100).boxed()
  676.                 .filter(i -> i % 2 != 0);
  677.         Stream<Integer> stream2 = IntStream.rangeClosed(101, 200).boxed()
  678.                 .filter(i -> i % 3 != 0);
  679.         Stream.concat(stream1, stream2)
  680.                 .forEach(System.out::println);
  681.         init22();
  682.     }
  683.    
  684.     private void init22() {
  685.         BigDecimal t1 = new BigDecimal(134.23576185216913);
  686.         BigDecimal one = new BigDecimal(1);
  687.         BigDecimal speed = new BigDecimal(200000000).pow(2);
  688.         BigDecimal lightsSpeed = new BigDecimal(299800000).pow(2);
  689.  
  690.         MathContext mc = new MathContext(2, RoundingMode.HALF_UP);
  691.         System.out.println(t1.subtract((t1.multiply(SquareRoot.bigSqrt(one.subtract(speed.divide(lightsSpeed,mc)))))));
  692.         init23();
  693.     }
  694.    
  695.     private void init23() {
  696.         GenericParticle electron = BasicGenericParticle.ELECTRON;
  697.         GenericParticle hydrogen = BasicGenericParticle.HYDROGEN;
  698.         GenericParticle water = new GenericParticleBuilder()
  699.                 .name("water").name("h2o2")
  700. //                .component(/*components*/)
  701.                 .build();
  702.         init24();
  703.     }
  704.    
  705.     private void init24() {
  706.         for (int y = 0; y < 5; y++) {
  707.             for (int x = y; x < 10; x += 2) {
  708.                 System.out.println(x + y);
  709.             }
  710.         }
  711.         init25();
  712.     }
  713.    
  714.     private void init25() {
  715.         doMyDoubleLoop(5, y -> y + 1, 10, x -> x + 2, (x, y) -> x + y, System.out::println);
  716.         init26();
  717.     }
  718.    
  719.     private void init26() {
  720.         doMyInternalDoubleLoop((x, y) -> x + y, System.out::println);
  721.         init27();
  722.     }
  723.    
  724.     private void doMyDoubleLoop(
  725.             final int yEnd, final IntUnaryOperator yIncrementOperator,
  726.             final int xEnd, final IntUnaryOperator xIncrementOperator,
  727.             final IntBinaryOperator combiner, final IntConsumer consumer
  728.     ) {
  729.         for (int y = 0; y < yEnd; y = yIncrementOperator.applyAsInt(y)) {
  730.             for (int x = y; x < xEnd; x = xIncrementOperator.applyAsInt(x)) {
  731.                 consumer.accept(combiner.applyAsInt(x, y));
  732.             }
  733.         }
  734.     }
  735.    
  736.     private void doMyInternalDoubleLoop(final IntBinaryOperator combiner, final IntConsumer consumer) {
  737.         for (int y = 0; y < 5; y++) {
  738.             for (int x = y; x < 10; x += 2) {
  739.                 consumer.accept(combiner.applyAsInt(x, y));
  740.             }
  741.         }
  742.     }
  743.    
  744.     private IntStream doMyInternalDoubleLoopRenewed(final IntBinaryOperator combiner, final IntConsumer consumer) {
  745.         //TODO is there a way to return it as an IntStream without consuming memory, thus making it lazy?
  746.         for (int y = 0; y < 5; y++) {
  747.             for (int x = y; x < 10; x += 2) {
  748.                 consumer.accept(combiner.applyAsInt(x, y));
  749.             }
  750.         }
  751.         return null;
  752.     }
  753.    
  754.     private void init27() {
  755.         Map<Integer, Long> coinCount = new Random().ints(10000, 0, 2)
  756.                 .boxed()
  757.                 .collect(Collectors.groupingBy(i -> i, Collectors.counting()));
  758.         coinCount.forEach((k, v) -> System.out.println("Key: " + k + " / Value: " + v));
  759.         init28();
  760.     }
  761.    
  762.     private void init28() {
  763.         int[] ints = new int[10];
  764.         int ints2[] = new int[10];
  765.         init29();
  766.     }
  767.    
  768.     private void init29() {
  769. //        int x = 0;
  770. //        int y = 0;
  771. //        int w = 10;
  772. //        int h = 10;
  773. //        Picture picture = null;
  774. //        IntStream.range(x, x + w)
  775. //                .parallel()
  776. //                .boxed()
  777. //                .flatMap(xVal -> IntStream.range(y, y + h).parallel().mapToObj(yVal -> new IntTuple(xVal, yVal)))
  778. //                .forEach(tuple -> averagePixel(picture, tuple));
  779.         init30();
  780.     }
  781.    
  782.     private void init30() {
  783.         Consumer<MyEnum> myMethod = MyEnum::myMethod;
  784.         init31();
  785.     }
  786.    
  787.     private void init31() {
  788. //        //little benchmark
  789. //        
  790. //        //setup byte arrays
  791. //        List<byte[]> arrays = createByteArrays(1000);
  792. //        
  793. //        //warmup
  794. //        arrays.forEach(this::byteArrayCheck12);
  795. //        arrays.forEach(this::byteArrayCheck3);
  796. //        arrays.forEach(this::byteArrayCheck4);
  797. //        arrays.forEach(this::byteArrayCheck5);
  798. //        
  799. //        //benchmark
  800. //        benchmark(arrays, this::byteArrayCheck12, "byteArrayCheck12");
  801. //        benchmark(arrays, this::byteArrayCheck3, "byteArrayCheck3");
  802. //        benchmark(arrays, this::byteArrayCheck4, "byteArrayCheck4");
  803. //        benchmark(arrays, this::byteArrayCheck5, "byteArrayCheck5");
  804.         init32();
  805.     }
  806.    
  807.     private void init32() {
  808.         byte a = 0;
  809.         byte b = 0;
  810.         byte c = -17;
  811.         byte d = 55;
  812.         byte e = -55;
  813.         byte f = 17;
  814.         long z = a | b | c | d | e | f;
  815.         System.out.println("z = " + z);
  816.         init33();
  817.     }
  818.    
  819.     private void init33() {
  820.         Float alpha = +0.0f;
  821.         Float beta = -0.0f;
  822.         boolean equal = alpha.equals(beta);
  823.         System.out.println("Equal: " + equal);
  824.  
  825.         boolean equality = alpha.floatValue() == beta.floatValue();
  826.         System.out.println("Equality: " + equality);
  827.         init34();
  828.     }
  829.    
  830.     private void init34() {
  831.         byte a = 1;
  832.         byte b = 3;
  833.         byte c = 7;
  834.         byte d = 11;
  835.         int z = a + b + c + d;
  836.         System.out.println("z = " + z);
  837.        
  838.         byte[] byteArray = new byte[] { a, b, c, d };
  839.         ByteBuffer byteBuffer = ByteBuffer.wrap(byteArray);
  840.         int[] intArray = new int[1];
  841.         byteBuffer.asIntBuffer().get(intArray);
  842.         System.out.println("intArray[0] = " + intArray[0]);
  843.         init35();
  844.     }
  845.    
  846.     private void init35() {
  847.         int ៛ = 0;
  848.         int ៛៛ = 0;
  849.         int ௹ = 1;
  850.         int ௹௹   = 1;
  851.         int ៛៛៛ = ៛*௹+៛៛/௹௹;
  852.         System.out.println("៛៛៛ = " + ៛៛៛);
  853.         init36();
  854.     }
  855.    
  856.     private void init36() {
  857.         String str1 = "a";
  858.         String str2 = "a@";
  859.         String str3 = "a@@a";
  860.         String str4 = "a#@a";
  861.         List<Character> characters = Arrays.asList('@', '#', '$', '%');
  862.  
  863.         System.out.println("stringMatchesChars(str1, characters) = " + stringMatchesChars(str1, characters));
  864.         System.out.println("stringMatchesChars(str2, characters) = " + stringMatchesChars(str2, characters));
  865.         System.out.println("stringMatchesChars(str3, characters) = " + stringMatchesChars(str3, characters));
  866.         System.out.println("stringMatchesChars(str4, characters) = " + stringMatchesChars(str4, characters));
  867.         init37();
  868.     }
  869.    
  870.     private void init37() {
  871.         String[] array = {"a", "b", "c", "d", "e", "f"};
  872.         for (int i = array.length; i--!=0; ) {
  873.             System.out.println("array[i] = " + array[i]);
  874.         }
  875.         init38();
  876.     }
  877.    
  878.     private void init38() {
  879.         register(event -> System.out.println("Test"));
  880.         init39();
  881.     }
  882.    
  883.     private void init39() {
  884.         String[] array = {"a", "b", "c"};
  885.         Collections.shuffle(Arrays.asList(array));
  886.         System.out.println("array = " + Arrays.toString(array));
  887.         init40();
  888.     }
  889.    
  890.     private void init40() {
  891.         Random random = new Random();
  892.         String randomString = IntStream.concat(
  893.                 random.ints(8, 'a', 'z'),
  894.                 random.ints(8, 'A', 'Z')
  895.         )
  896.                 .collect(
  897.                         StringBuilder::new,
  898.                         (sb, i) -> sb.append((char)i),
  899.                         (sb1, sb2) -> sb1.append(sb2)
  900.                 ).toString();
  901.         System.out.println("randomString = " + randomString);
  902.         init41();
  903.     }
  904.    
  905.     private void init41() {
  906.         List<Integer> list = Arrays.asList(1, 3, 5, 7, 9, 11);
  907.         Iterator<Integer> iterator = list.iterator();
  908.         Spliterator<Integer> spliterator = Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED);
  909.         Stream<Integer> stream = StreamSupport.stream(spliterator, false);
  910.         stream.forEach(System.out::println);
  911.         init42();
  912.     }
  913.    
  914.     private void init42() {
  915.        
  916.     }
  917.    
  918.     public void shuffleArray(final Object[] array) {
  919.         Collections.shuffle(Arrays.asList(Objects.requireNonNull(array, "array")));
  920.     }
  921.    
  922.     private void register(final EventListener eventListener) {
  923.         System.out.println("Registered " + eventListener);
  924.     }
  925.    
  926.     private static class Event { }
  927.    
  928.     @Retention(RetentionPolicy.RUNTIME)
  929.     @Target(ElementType.METHOD)
  930.     private static @interface Annotation { }
  931.    
  932.     private static interface EventListener {
  933.         @Annotation
  934.         void apply(final Event event);
  935.     }
  936.    
  937.     private static class EventListenerImpl implements EventListener {
  938.         @Override
  939.         public void apply(final Event event) {
  940.             throw new UnsupportedOperationException("Not supported yet.");
  941.         }
  942.     }
  943.    
  944.     private boolean stringMatchesChars(final String str, final List<Character> characters) {
  945.         return (str.chars()
  946.                 .filter(ch -> characters.contains((char)ch))
  947.                 .count() == 1);
  948.     }
  949.    
  950.     private void benchmark(final List<byte[]> arrays, final Consumer<byte[]> method, final String name) {
  951.         long start = System.nanoTime();
  952.         arrays.forEach(method);
  953.         long end = System.nanoTime();
  954.         double nanosecondsPerIteration = (end - start) * 1d / arrays.size();
  955.         System.out.println("Benchmark: " + name + " / iterations: " + arrays.size() + " / time per iteration: " + nanosecondsPerIteration + "ns");
  956.     }
  957.    
  958.     private List<byte[]> createByteArrays(final int amount) {
  959.         Random random = new Random();
  960.         List<byte[]> resultList = new ArrayList<>();
  961.         for (int i = 0; i < amount; i++) {
  962.             byte[] byteArray = new byte[4096];
  963.             byteArray[random.nextInt(4096)] = 1;
  964.             resultList.add(byteArray);
  965.         }
  966.         return resultList;
  967.     }
  968.    
  969.     private boolean byteArrayCheck12(final byte[] array) {
  970.         long sum = 0L;
  971.         for (byte b : array) {
  972.             sum += b;
  973.         }
  974.         return (sum == 0);
  975.     }
  976.    
  977.     private boolean byteArrayCheck3(final byte[] array) {
  978.         for (byte b : array) {
  979.             if (b != 0) {
  980.                 return false;
  981.             }
  982.         }
  983.         return true;
  984.     }
  985.    
  986.     private boolean byteArrayCheck4(final byte[] array) {
  987.         return (IntStream.range(0, array.length).map(i -> array[i]).sum() != 0);
  988.     }
  989.    
  990.     private boolean byteArrayCheck5(final byte[] array) {
  991.         return IntStream.range(0, array.length).map(i -> array[i]).anyMatch(i -> i != 0);
  992.     }
  993.    
  994.     private List<Pixel> getNeighbours(final Picture picture, final IntTuple intTuple) {
  995.         List<Pixel> pixels = new ArrayList<>();
  996.         for (int x = intTuple.x - 1; x <= intTuple.x + 1; x++) {
  997.             for (int y = intTuple.y - 1; y <= intTuple.y + 1; y++) {
  998.                 pixels.add(picture.getPixel(x, y));
  999.             }
  1000.         }
  1001.         return pixels;
  1002.     }
  1003.    
  1004.     private void averagePixel(final Picture picture, final IntTuple intTuple) {
  1005.         double red = 0d;
  1006.         double green = 0d;
  1007.         double blue = 0d;
  1008.         List<Pixel> neighbours = getNeighbours(picture, intTuple);
  1009.         for (Pixel pixel : neighbours) {
  1010.             red += pixel.getRed();
  1011.             green += pixel.getGreen();
  1012.             blue += pixel.getBlue();
  1013.         }
  1014.         Pixel pixel = picture.getPixel(intTuple.x, intTuple.y);
  1015.         pixel.setRed((int)(red / neighbours.size()));
  1016.         pixel.setGreen((int)(green / neighbours.size()));
  1017.         pixel.setBlue((int)(blue / neighbours.size()));
  1018.     }
  1019.    
  1020.     private class Pixel {
  1021.         public int getRed() {
  1022.             return 0;
  1023.         }
  1024.         public int getGreen() {
  1025.             return 0;
  1026.         }
  1027.         public int getBlue() {
  1028.             return 0;
  1029.         }
  1030.         public void setRed(int red) { }
  1031.         public void setGreen(int red) { }
  1032.         public void setBlue(int red) { }
  1033.     }
  1034.            
  1035.     private class Picture {
  1036.         public Pixel getPixel(int x, int y) {
  1037.             return null;
  1038.         }
  1039.     }
  1040.    
  1041.     private class IntTuple {
  1042.         public final int x;
  1043.         public final int y;
  1044.  
  1045.         public IntTuple(final int x, final int y) {
  1046.             this.x = x;
  1047.             this.y = y;
  1048.         }
  1049.     }
  1050. }
  1051.  
  1052. @FunctionalInterface
  1053. interface Test {
  1054.     void test();
  1055.    
  1056.     @Override
  1057.     boolean equals(Object other);
  1058. }
  1059.  
  1060. class BankAccount implements Serializable {
  1061.     private static final long serialVersionUID = 684656564655528L;
  1062.    
  1063.     private final String clientName;
  1064.     private BigDecimal balance;
  1065.    
  1066.     public BankAccount(final String clientName, final BigDecimal balance) {
  1067.         this.clientName = Objects.requireNonNull(clientName);
  1068.         this.balance = Objects.requireNonNull(balance);
  1069.     }
  1070.    
  1071.     private Object writeReplace() {
  1072.         return new SerializationProxy(this);
  1073.     }
  1074.    
  1075.     private void readObject(final ObjectInputStream stream) throws InvalidObjectException {
  1076.         throw new InvalidObjectException("Proxy required");
  1077.     }
  1078.    
  1079.     private static class SerializationProxy implements Serializable {
  1080.         private static final long serialVersionUID = 5684551235489465L;
  1081.        
  1082.         private final String clientName;
  1083.         private final BigDecimal balance;
  1084.        
  1085.         private SerializationProxy(final BankAccount bankAccount) {
  1086.             this.clientName = bankAccount.clientName;
  1087.             this.balance = bankAccount.balance;
  1088.         }
  1089.        
  1090.         private Object readResolve() {
  1091.             return new BankAccount(clientName, balance);
  1092.         }
  1093.     }
  1094. }
  1095.  
  1096. enum Component {
  1097.     ELECTRON, PROTON, NEUTRON;
  1098. }
  1099.  
  1100. interface GenericParticle {
  1101.     List<String> getNames();
  1102.  
  1103.     List<Component> getComponents();
  1104. }
  1105.  
  1106. enum BasicGenericParticle implements GenericParticle {
  1107.     ELECTRON(
  1108.             Arrays.asList("electron", "e"),
  1109.             Arrays.asList(Component.ELECTRON)
  1110.     ),
  1111.     HYDROGEN(
  1112.             Arrays.asList("hydrogen", "h"),
  1113.             Arrays.asList(Component.ELECTRON, Component.PROTON)
  1114.     )
  1115.     ;
  1116.  
  1117.     private final List<String> names;
  1118.     private final List<Component> components;
  1119.  
  1120.     private BasicGenericParticle(final List<String> names, final List<Component> components) {
  1121.         this.names = names;
  1122.         this.components = components;
  1123.     }
  1124.  
  1125.     @Override
  1126.     public List<String> getNames() {
  1127.         return new ArrayList<>(names);
  1128.     }
  1129.  
  1130.     @Override
  1131.     public List<Component> getComponents() {
  1132.         return new ArrayList<>(components);
  1133.     }
  1134. }
  1135.  
  1136. class GenericParticleBuilder {
  1137.     private List<String> names = new ArrayList<>();
  1138.     private List<Component> components = new ArrayList<>();
  1139.  
  1140.     public GenericParticleBuilder name(final String name) {
  1141.         names.add(name);
  1142.         return this;
  1143.     }
  1144.  
  1145.     public GenericParticleBuilder component(final Component component) {
  1146.         components.add(component);
  1147.         return this;
  1148.     }
  1149.  
  1150.     public GenericParticle build() {
  1151.         return new GenericParticleImpl(names, components);
  1152.     }
  1153.  
  1154.     private static class GenericParticleImpl implements GenericParticle {
  1155.         private List<String> names = new ArrayList<>();
  1156.         private List<Component> components = new ArrayList<>();
  1157.  
  1158.         public GenericParticleImpl(final List<String> names, final List<Component> components) {
  1159.             this.names = names;
  1160.             this.components = components;
  1161.         }
  1162.  
  1163.         @Override
  1164.         public List<String> getNames() {
  1165.             return new ArrayList<>(names);
  1166.         }
  1167.  
  1168.         @Override
  1169.         public List<Component> getComponents() {
  1170.             return new ArrayList<>(components);
  1171.         }
  1172.     }
  1173. }
  1174.  
  1175. class SquareRoot {
  1176.     private static final BigDecimal SQRT_DIG = new BigDecimal(150);
  1177.     private static final BigDecimal SQRT_PRE = new BigDecimal(10).pow(SQRT_DIG.intValue());
  1178.  
  1179.     /**
  1180.      * Private utility method used to compute the square root of a BigDecimal.
  1181.      *
  1182.      * @author Luciano Culacciatti
  1183.      * @url http://www.codeproject.com/Tips/257031/Implementing-SqrtRoot-in-BigDecimal
  1184.      */
  1185.     private static BigDecimal sqrtNewtonRaphson  (BigDecimal c, BigDecimal xn, BigDecimal precision){
  1186.         BigDecimal fx = xn.pow(2).add(c.negate());
  1187.         BigDecimal fpx = xn.multiply(new BigDecimal(2));
  1188.         BigDecimal xn1 = fx.divide(fpx,2*SQRT_DIG.intValue(),RoundingMode.HALF_DOWN);
  1189.         xn1 = xn.add(xn1.negate());
  1190.         BigDecimal currentSquare = xn1.pow(2);
  1191.         BigDecimal currentPrecision = currentSquare.subtract(c);
  1192.         currentPrecision = currentPrecision.abs();
  1193.         if (currentPrecision.compareTo(precision) <= -1){
  1194.             return xn1;
  1195.         }
  1196.         return sqrtNewtonRaphson(c, xn1, precision);
  1197.     }
  1198.  
  1199.     /**
  1200.      * Uses Newton Raphson to compute the square root of a BigDecimal.
  1201.      *
  1202.      * @author Luciano Culacciatti
  1203.      * @url http://www.codeproject.com/Tips/257031/Implementing-SqrtRoot-in-BigDecimal
  1204.      */
  1205.     public static BigDecimal bigSqrt(BigDecimal c){
  1206.         return sqrtNewtonRaphson(c,new BigDecimal(1),new BigDecimal(1).divide(SQRT_PRE));
  1207.     }
  1208. }
  1209.  
  1210. class OptionalDoubleImproved {
  1211.     private static final OptionalDoubleImproved EMPTY = OptionalDoubleImproved.of(OptionalDouble.empty());
  1212.  
  1213.     private final OptionalDouble optionalDouble;
  1214.  
  1215.     private OptionalDoubleImproved(final OptionalDouble optionalDouble) {
  1216.         this.optionalDouble = Objects.requireNonNull(optionalDouble);
  1217.     }
  1218.  
  1219.     public static OptionalDoubleImproved of(final OptionalDouble optionalDouble) {
  1220.         return new OptionalDoubleImproved(optionalDouble);
  1221.     }
  1222.  
  1223.     public OptionalDoubleImproved applyFunction(final DoubleBinaryOperator operator, final OptionalDouble operand) {
  1224.         Objects.requireNonNull(operator);
  1225.         Objects.requireNonNull(operand);
  1226.         if (!optionalDouble.isPresent() || !operand.isPresent()) {
  1227.             return EMPTY;
  1228.         }
  1229.         return OptionalDoubleImproved.of(OptionalDouble.of(operator.applyAsDouble(optionalDouble.getAsDouble(), operand.getAsDouble())));
  1230.     }
  1231.  
  1232.     public OptionalDouble get() {
  1233.         return optionalDouble;
  1234.     }
  1235.  
  1236.     @Override
  1237.     public int hashCode() {
  1238.         int hash = 7;
  1239.         hash = 53 * hash + Objects.hashCode(this.optionalDouble);
  1240.         return hash;
  1241.     }
  1242.  
  1243.     @Override
  1244.     public boolean equals(Object obj) {
  1245.         if (obj == null) {
  1246.             return false;
  1247.         }
  1248.         if (getClass() != obj.getClass()) {
  1249.             return false;
  1250.         }
  1251.         final OptionalDoubleImproved other = (OptionalDoubleImproved) obj;
  1252.         if (!Objects.equals(this.optionalDouble, other.optionalDouble)) {
  1253.             return false;
  1254.         }
  1255.         return true;
  1256.     }
  1257.  
  1258.     @Override
  1259.     public String toString() {
  1260.         return "OptionalDoubleImproved[" + optionalDouble + "]";
  1261.     }
  1262. }
  1263.  
  1264. //enum Operation implements DoubleBinaryOperator {
  1265. //    PLUS("+") {
  1266. //        @Override
  1267. //        public double applyAsDouble(final double left, final double right) {
  1268. //            return left + right;
  1269. //        }
  1270. //    },
  1271. //    MINUS("-") {
  1272. //        @Override
  1273. //        public double applyAsDouble(final double left, final double right) {
  1274. //            return left - right;
  1275. //        }
  1276. //    },
  1277. //    MULTIPLY("*") {
  1278. //        @Override
  1279. //        public double applyAsDouble(final double left, final double right) {
  1280. //            return left * right;
  1281. //        }
  1282. //    },
  1283. //    DIVIDE("/") {
  1284. //        @Override
  1285. //        public double applyAsDouble(final double left, final double right) {
  1286. //            return left / right;
  1287. //        }
  1288. //    };
  1289. //
  1290. //    private final String symbol;
  1291. //
  1292. //    private Operation(final String symbol) {
  1293. //        this.symbol = symbol;
  1294. //    }
  1295. //
  1296. //    public String getSymbol() {
  1297. //        return symbol;
  1298. //    }
  1299. //}
  1300.  
  1301. enum Operation implements DoubleBinaryOperator {
  1302.     PLUS    ("+", (l, r) -> l + r),
  1303.     MINUS   ("-", (l, r) -> l - r),
  1304.     MULTIPLY("*", (l, r) -> l * r),
  1305.     DIVIDE  ("/", (l, r) -> l / r);
  1306.  
  1307.     private final String symbol;
  1308.     private final DoubleBinaryOperator binaryOperator;
  1309.  
  1310.     private Operation(final String symbol, final DoubleBinaryOperator binaryOperator) {
  1311.         this.symbol = symbol;
  1312.         this.binaryOperator = binaryOperator;
  1313.     }
  1314.  
  1315.     public String getSymbol() {
  1316.         return symbol;
  1317.     }
  1318.  
  1319.     @Override
  1320.     public double applyAsDouble(final double left, final double right) {
  1321.         return binaryOperator.applyAsDouble(left, right);
  1322.     }
  1323. }
  1324.  
  1325. enum ContentType {
  1326.     TITLE("$$title$$",SubType.MAIL),
  1327.     BODY("$$body$$",SubType.MAIL),
  1328.     MESSAGE("$$message$$",SubType.MAIL),
  1329.     EVENTS("$$events$$",SubType.DEFAULT);
  1330.  
  1331.     private static final EnumMap<SubType, Set<ContentType>> SETS_BY_SUBTYPE;
  1332.     static {
  1333.         SETS_BY_SUBTYPE = Arrays.stream(values())
  1334.                 .collect(Collectors.groupingBy(
  1335.                         ContentType::getSubType,
  1336.                         () -> new EnumMap<>(SubType.class),
  1337.                         Collectors.toSet()
  1338.                 ));
  1339.     }
  1340.  
  1341.     private final String replaceWord;
  1342.     private final SubType subType;
  1343.  
  1344.     private ContentType(final String replaceWord, final SubType subType) {
  1345.         this.replaceWord = replaceWord;
  1346.         this.subType = subType;
  1347.     }
  1348.  
  1349.     public String getReplaceWord() {
  1350.         return replaceWord;
  1351.     }
  1352.  
  1353.     private SubType getSubType() {
  1354.         return subType;
  1355.     }
  1356.  
  1357.     public static Set<ContentType> values(final SubType subType) {
  1358.         return SETS_BY_SUBTYPE.get(subType);
  1359.     }
  1360. }
  1361.  
  1362. enum SubType {
  1363.     MAIL,
  1364.     DEFAULT;
  1365. }
  1366.  
  1367. class Pet {
  1368.    
  1369. }
  1370.  
  1371. class Pair<T, U> {
  1372.     private final T t;
  1373.     private final U u;
  1374.    
  1375.     public Pair(final T t, final U u) {
  1376.         this.t = t;
  1377.         this.u = u;
  1378.     }
  1379.    
  1380.     @Override
  1381.     public String toString() {
  1382.         return "(" + t + ", " + u + ")";
  1383.     }
  1384. }
  1385.  
  1386. class CustomOptionalOld<T> {
  1387.     private final Optional<T> optional;
  1388.  
  1389.     private CustomOptionalOld() {
  1390.         this.optional = Optional.empty();
  1391.     }
  1392.  
  1393.     private CustomOptionalOld(final T value) {
  1394.         this.optional = Optional.of(value);
  1395.     }
  1396.  
  1397.     private CustomOptionalOld(final Optional<T> optional) {
  1398.         this.optional = optional;
  1399.     }
  1400.  
  1401.     public Optional<T> getOptional() {
  1402.         return optional;
  1403.     }
  1404.  
  1405.     public static <T> CustomOptionalOld<T> empty() {
  1406.         return new CustomOptionalOld<>();
  1407.     }
  1408.  
  1409.     public static <T> CustomOptionalOld<T> of(final T value) {
  1410.         return new CustomOptionalOld<>(value);
  1411.     }
  1412.  
  1413.     public static <T> CustomOptionalOld<T> ofNullable(final T value) {
  1414.         return (value == null) ? empty() : of(value);
  1415.     }
  1416.  
  1417.     public T get() {
  1418.         return optional.get();
  1419.     }
  1420.  
  1421.     public boolean isPresent() {
  1422.         return optional.isPresent();
  1423.     }
  1424.  
  1425.     public void ifPresent(final Consumer<? super T> consumer) {
  1426.         optional.ifPresent(consumer);
  1427.     }
  1428.  
  1429.     public CustomOptionalOld<T> filter(final Predicate<? super T> predicate) {
  1430.         return new CustomOptionalOld<>(optional.filter(predicate));
  1431.     }
  1432.  
  1433.     public <U> CustomOptionalOld<U> map(final Function<? super T, ? extends U> mapper) {
  1434.         return new CustomOptionalOld<>(optional.map(mapper));
  1435.     }
  1436.  
  1437.     public <U> CustomOptionalOld<U> flatMap(final Function<? super T, ? extends CustomOptionalOld<U>> mapper) {
  1438.         return new CustomOptionalOld<>(optional.flatMap(mapper.andThen(CustomOptionalOld::getOptional)));
  1439. //        return new CustomOptionalOld<>(optional.flatMap(mapper.andThen(cu -> cu.getOptional())));
  1440.     }
  1441.  
  1442.     public T orElse(final T other) {
  1443.         return optional.orElse(other);
  1444.     }
  1445.  
  1446.     public T orElseGet(final Supplier<? extends T> other) {
  1447.         return optional.orElseGet(other);
  1448.     }
  1449.  
  1450.     public <X extends Throwable> T orElseThrow(final Supplier<? extends X> exceptionSuppier) throws X {
  1451.         return optional.orElseThrow(exceptionSuppier);
  1452.     }
  1453.  
  1454.     public Stream<T> flatStream() {
  1455.         if (!optional.isPresent()) {
  1456.             return Stream.empty();
  1457.         }
  1458.         return Stream.of(get());
  1459.     }
  1460.  
  1461.     public T getTOrNull() {
  1462.         if (!optional.isPresent()) {
  1463.             return null;
  1464.         }
  1465.         return get();
  1466.     }
  1467.  
  1468.     @Override
  1469.     public boolean equals(final Object obj) {
  1470.         return optional.equals(obj);
  1471.     }
  1472.  
  1473.     @Override
  1474.     public int hashCode() {
  1475.         return optional.hashCode();
  1476.     }
  1477.  
  1478.     @Override
  1479.     public String toString() {
  1480.         return optional.toString();
  1481.     }
  1482. }
  1483.  
  1484. class AnimalAI {
  1485.    
  1486. }
  1487.  
  1488. class Lion extends AnimalAI {
  1489.    
  1490. }
  1491.  
  1492. class Zebra extends AnimalAI {
  1493.    
  1494. }
  1495.  
  1496. class YourClass {
  1497.     static {
  1498.         System.out.println("I got loaded!");
  1499.     }
  1500. }
  1501.  
  1502. class CustomList<T> extends ArrayList<T> {
  1503.     public void printRandom() {
  1504.         System.out.println("random");
  1505.     }
  1506. }
  1507.  
  1508. class Player {
  1509.    public String player_name;
  1510.    public int number;
  1511.  
  1512.    public int getNumber() {
  1513.        return number;
  1514.    }
  1515. }
  1516.  
  1517. class User {
  1518.  
  1519.     @Override
  1520.     public String toString() {
  1521.         return id + " - " + username;
  1522.     }
  1523.  
  1524.     int id;
  1525.     String username;
  1526.  
  1527.     public User() {
  1528.     }
  1529.  
  1530.     public User(int id, String username) {
  1531.         this.id = id;
  1532.         this.username = username;
  1533.     }
  1534.  
  1535.     public void setUsername(String username) {
  1536.         this.username = username;
  1537.     }
  1538.  
  1539.     public void setId(int id) {
  1540.         this.id = id;
  1541.     }
  1542.  
  1543.     public String getUsername() {
  1544.         return username;
  1545.     }
  1546.  
  1547.     public int getId() {
  1548.         return id;
  1549.     }
  1550. }
  1551.  
  1552. @FunctionalInterface
  1553. interface CustomPredicate<T> extends Function<T, Boolean> {
  1554.     boolean test(T value);
  1555.  
  1556.     @Override
  1557.     default Boolean apply(T t) {
  1558.         return test(t);
  1559.     }
  1560. }
  1561.  
  1562. class Invoice {
  1563.     String company;
  1564.     String invoice_number;
  1565.     BigDecimal unit_price;
  1566.     BigDecimal quantity;
  1567.  
  1568.     public Invoice() {
  1569.         unit_price = BigDecimal.ZERO;
  1570.         quantity = BigDecimal.ZERO;
  1571.     }
  1572.  
  1573.     public Invoice(String company, String invoice_number, BigDecimal unit_price, BigDecimal quantity) {
  1574.         this.company = company;
  1575.         this.invoice_number = invoice_number;
  1576.         this.unit_price = unit_price;
  1577.         this.quantity = quantity;
  1578.     }
  1579.  
  1580.     public BigDecimal total() {
  1581.         return unit_price.multiply(quantity);
  1582.     }
  1583.  
  1584.     public void setUnit_price(BigDecimal unit_price) {
  1585.         this.unit_price = unit_price;
  1586.     }
  1587.  
  1588.     public void setQuantity(BigDecimal quantity) {
  1589.         this.quantity = quantity;
  1590.     }
  1591.  
  1592.     public void setInvoice_number(String invoice_number) {
  1593.         this.invoice_number = invoice_number;
  1594.     }
  1595.  
  1596.     public void setCompany(String company) {
  1597.         this.company = company;
  1598.     }
  1599.  
  1600.     public BigDecimal getUnit_price() {
  1601.         return unit_price;
  1602.     }
  1603.  
  1604.     public BigDecimal getQuantity() {
  1605.         return quantity;
  1606.     }
  1607.  
  1608.     public String getInvoice_number() {
  1609.         return invoice_number;
  1610.     }
  1611.  
  1612.     public String getCompany() {
  1613.         return company;
  1614.     }
  1615. }
  1616.  
  1617. class Person {
  1618.     private String firstName;
  1619.     private String lastName;
  1620.  
  1621.     public Person(final String firstName, final String lastName) {
  1622.         this.firstName = firstName;
  1623.         this.lastName = lastName;
  1624.     }
  1625.  
  1626.     public String getFirstName() {
  1627.         return firstName;
  1628.     }
  1629.  
  1630.     public void setFirstName(String firstName) {
  1631.         this.firstName = firstName;
  1632.     }
  1633.  
  1634.     public String getLastName() {
  1635.         return lastName;
  1636.     }
  1637.  
  1638.     public void setLastName(String lastName) {
  1639.         this.lastName = lastName;
  1640.     }
  1641.    
  1642.     @Override
  1643.     public String toString() {
  1644.         return firstName + " " + lastName;
  1645.     }
  1646. }
  1647.  
  1648. class Car implements Drivable {
  1649.     @Override
  1650.     public void drive() {
  1651.         System.out.println("Starting to drive");
  1652.     }
  1653.  
  1654.     @Override
  1655.     public int getWheelCount() {
  1656.         return 0;
  1657.     }
  1658. }
  1659.  
  1660. interface Drivable {
  1661.     public void drive();
  1662.    
  1663.     public int getWheelCount();
  1664. }
  1665.  
  1666. class UnrelatedClass implements UnrelatedInterfaceDefault {
  1667.     @Override
  1668.     public void unrelate2() {
  1669.         System.out.println("Unrelated");
  1670.     }
  1671. }
  1672.  
  1673. interface UnrelatedInterfaceDefault extends UnrelatedInterfaceOne, UnrelatedInterfaceTwo {
  1674.     default public void unrelate() {
  1675. //        UnrelatedInterfaceOne.super.unrelate2();
  1676. //        UnrelatedInterfaceTwo.super.unrelate2();
  1677. //        ((UnrelatedInterfaceOne)this).unrelate2();
  1678. //        ((UnrelatedInterfaceTwo)this).unrelate2();
  1679.         unrelate2();
  1680.     }
  1681. }
  1682.  
  1683. interface UnrelatedInterfaceOne {
  1684.     public void unrelate2();
  1685. }
  1686.  
  1687. interface UnrelatedInterfaceTwo {
  1688.     public void unrelate2();
  1689. }
  1690.  
  1691. class SuperClass {
  1692.     public SuperClass(){
  1693.         System.out.println("Super Constructor");
  1694.     }
  1695.     public SuperClass(int i){
  1696.         this();
  1697.         System.out.println("Parameterized Super Constructor");
  1698.     }
  1699. }
  1700. class SubClass extends SuperClass {
  1701.     public SubClass(){
  1702.         System.out.println("Sub Constructor");
  1703.     }
  1704.     public SubClass(int i){
  1705.         super(i); /* Need to call **this()** here .. Is this possible? */
  1706.         System.out.println("Parameterized  Sub Constructor");
  1707.     }
  1708. }
  1709.  
  1710. class Employee {
  1711.     private int empSalary;
  1712.     private String empName;
  1713.  
  1714.     public int getEmpSalary() {
  1715.         return empSalary;
  1716.     }
  1717.    
  1718.     public String getEmpName() {
  1719.         return empName;
  1720.     }
  1721. }
  1722.  
  1723. class MoneyFormatCell extends TableCell<Factura, BigDecimal> {
  1724.     public MoneyFormatCell() {
  1725.     }
  1726. }
  1727.  
  1728. class Factura {
  1729.    
  1730. }
  1731.  
  1732. class MutableNonSafeInt {
  1733.     private int i = 0;
  1734.  
  1735.     public void increase() {
  1736.         i++;
  1737.     }
  1738.  
  1739.     public int get() {
  1740.         return i;
  1741.     }
  1742. }
  1743.  
  1744. interface Notifiable {
  1745.  
  1746. }
  1747.  
  1748. class NotifiableImpl1 implements Notifiable {
  1749.  
  1750. }
  1751.  
  1752. class NotifiableImpl2 implements Notifiable {
  1753.  
  1754. }
  1755.  
  1756. class NotifiableImpl3 implements Notifiable {
  1757.  
  1758. }
  1759.  
  1760. interface Number {
  1761.     public int intValue();
  1762.  
  1763.     public long longValue();
  1764.  
  1765.     public float floatValue();
  1766.  
  1767.     public double doubleValue();
  1768.  
  1769.     default public byte byteValue() {
  1770.         return (byte)intValue();
  1771.     }
  1772.  
  1773.     default public short shortValue() {
  1774.         return (short)intValue();
  1775.     }
  1776. }
  1777. //
  1778. //class LinkedList {
  1779. //    private Node head = new Node();
  1780. //    private Node tail = new Node();
  1781. //    
  1782. //    {
  1783. //        connect(head, tail);
  1784. //    }
  1785. //    
  1786. //    public LinkedList() {
  1787. //        /* Constructor one */
  1788. //    }
  1789. //    
  1790. //    public LinkedList(final Object something) {
  1791. //        /* Constructor two */
  1792. //    }
  1793. //    
  1794. //    private void connect(Node head, Node tail) {
  1795. //        /* Connect the nodes */
  1796. //    }
  1797. //    
  1798. //    private class Node { }
  1799. //}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement