12/27/2018

[Java8] Lambda Expression

From Wikipedia, the free encyclopedia

In computer programming, an anonymous function (function literal, lambda abstraction, or lambda expression) is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to higher-order functions, or used for constructing the result of a higher-order function that needs to return a function.[1] If the function is only used once, or a limited number of times, an anonymous function may be syntactically lighter than using a named function. Anonymous functions are ubiquitous in functional programming languages and other languages with first-class functions, where they fulfill the same role for the function type as literals do for other data types.

What's a lambda expression in Java world?
A lambda expression is an unnamed block of code with a list of formal parameters and a body, or named an anonymous function.
It can be easily imagined with 3 parts: arguments list, arrow token and body. Let's see more examples.

() -> {}                // No parameters; result is void
() -> 42                // No parameters, expression body
() -> null              // No parameters, expression body
() -> { return 42; }    // No parameters, block body with return
() -> { System.gc(); }  // No parameters, void block body
() -> {                 // Complex block body with returns
  if (true) return 12;
  else {
    int result = 15;
    for (int i = 1; i < 10; i++)
      result *= i;
    return result;
} }
(int x) -> x+1              // Single declared-type parameter
(int x) -> { return x+1; }  // Single declared-type parameter
(x) -> x+1
x -> x+1
(String s) -> s.length()
(Thread t) -> { t.start(); }  // Single declared-type parameter
s -> s.length()               // Single inferred-type parameter
t -> { t.start(); }           // Single inferred-type parameter

(int x, int y) -> x+y  // Multiple declared-type parameters
(x, y) -> x+y          // Multiple inferred-type parameters
(x, int y) -> x+y    // Illegal: can't mix inferred and declared types
(x, final y) -> x+y  // Illegal: no modifiers with inferred types

Basically, we should use inferred-type parameters and simple statement as body while writing code.

12/22/2018

[Java8] Map with Mew Default Methods

Java 8 introduced the new default methods to Map interface which stores lazied-computed value and doesn't break map contract. We can be based on below to write clean code.

getOrDefault

Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.

   public void testGetOfDefault()
   {
      Map<String, Integer> studentGrades = new HashMap<>();
      Assert.assertThat(studentGrades.getOrDefault("Chris", 0), equalTo(new Integer(0)));
   }

forEach

Performs the give action for each entry in this map util all entries have been processed or the action throws an exception.

   public void testForEach()
   {
      Map<String, Integer> collector = new HashMap()
      { { put("A", 99); put("B", 80); put("C", 70); } };
      collector.forEach((key, value) -> System.out.println(String.format("%s => %s", key, value)));
   }

replaceAll

Replaces each entry's value with the result of invoking the given function on that entry util all entries have been processed or the function throws an exception.

   public void testReplaceAll()
   {
      Map<String, Integer> collector = new HashMap()
      { { put("A", 99); put("B", 82); put("C", 71); } };
      collector.replaceAll((key, value) -> value < 90 ? value + 10 : value);
      assertThat(collector, hasEntry("A", 99));
      assertThat(collector, hasEntry("B", 92));
      assertThat(collector, hasEntry("C", 81));
   }

putIfAbsent

If the specified key is not already associated with a value is mapped to null associates if with the given value and return null, else returns the current value.

   public void testPutIfAbsent()
   {
      Map<String, Integer> counters = new HashMap()
      {{ put("c0", 0); }};

      counters.putIfAbsent("c0", 99);
      counters.putIfAbsent("c1", 99);
      
      assertEquals(Integer.valueOf(0), counters.get("c0"));
      assertEquals(Integer.valueOf(99), counters.get("c1"));
   }

computeIfAbsent

If the specified key is not already associated with a value, attempts too compute its value using the given function and enters it into this map unless null.

   public void testComputeIfAbsent()
   {
      Map<String, List<Integer>> counters = new HashMap<>();
      counters.computeIfAbsent("key", k -> new ArrayList<>()).addAll(Arrays.asList(1, 3, 5));
      Assert.assertThat(counters.get("key"), hasItems(1, 3, 5));
   }

computeIfPresent

If the value for the specified key is present and not-null, attempts to compute a new mapping given the key and its current mapped value.

   public void testComputeIfPresent()
   {
      Map<String, Integer> map = new HashMap()
      {{
         put("key", 2);
      }};
      map.computeIfPresent("key", (k, v) -> v / 2);
      assertThat(map.get("key"), equalTo(1));
   }

merge

If the value for the specified key is present and non-null, attempts to compute a new mapping give the key and its current mapped value.

   public void testMergeValue()
   {
      Map<String, String> holder = new HashMap();
      holder.put("chris", "^^~");
      holder.merge("chris", "Java", (v1, v2) -> v1.concat(v2));
      Assert.assertThat(holder.get("chris"), is("^^~Java"));
   }
   

12/14/2018

[Java8] Optional

Java 8 SE introduces a new class called Optional that is inspired from Haskell and Scala. It's a class that encapsulates an option value. We can view Optional as a single value that either contains a value or not.

From Java definition

A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

Here are some test cases.

Creates the non-null and null value optional.

  @Test
   public void testCreate_NonNull_null_Optionals()
   {
      Optional<String> country = Optional.of("Taiwan");
      Assertions.assertTrue(country.isPresent());
      Assertions.assertEquals("Taiwan", country.get());

      Assertions.assertEquals(false, Optional.ofNullable(null).isPresent());
      Assertions.assertEquals("defaultValue", Optional.ofNullable(null).orElse("defaultValue"));
   }

Return value if present, otherwise return other.

   @Test
   public void testGetElseOption()
   {
      Optional<Date> current = Optional.ofNullable(null);
      Assertions.assertNotNull(current.orElse(new Date()));
   }
   

Return the value if present, otherwise invoke other and return the result of that invocation.

   @Test
   public void testOrElseGet()
   {
      Date dateNow = null;
Assertions.assertNotNull(Optional.ofNullable(dateNow).orElseGet(Date::new));
   }

Return the contained value, if present, otherwise throw an exception to be created by the provided supplier.

   @Test
   public void testOrElseThrow()
   {
      Date dateNow = null;
      Assertions.assertThrows(IllegalArgumentException.class, 
         () -> Optional.ofNullable(dateNow).orElseThrow(IllegalArgumentException::new));
   }

If a value is present, and the value matches the given predicate, return a describing the value, otherwise return an empty.

   @Test
   public void testFilter()
   {
      Optional<String> taipeiCity = Optional.of("Taipei").filter((v) -> v.contains("No.1 City"));
      Assertions.assertEquals(Optional.empty(), taipeiCity);

      Optional<String> county = Optional.of("Taiwan").filter(v -> v.contains("Taiwan"));
      Assertions.assertEquals("Taiwan", county.get());
   }

If a value is present, apply the provided {@code Optional}-bearing mapping function to it, return that result, otherwise return an empty {@code Optional}

   @Test
   public void testFlatMap()
   {
      Optional<Integer> numOp = Optional.of("111").flatMap(v -> Optional.of(Integer.valueOf(v)));
      Assertions.assertEquals(Integer.valueOf(111), numOp.get());
   }

In Java8 Optional is often be misused, optionals are not as easy as they seem. This tutorial will help us to avoid doing stupid code.

26 Reasons Why Using Optional Correctly Is Not Optional

12/12/2018

[Java8] BiFunction Functional Interface

From Wikipedia about Arity,

In logic, mathematics, and computer science, the arity /ˈærɪti/ (About this soundlisten) of a function or operation is the number of arguments or operands that the function takes

A binary function takes two arguments.
Example: {f(x,y)=2xy}

From Java definition

Represents a function that accepts two arguments and produces a result. This is the two arity specialization of Function.

here are some test cases to understand deeply biFunction.

   public void testFindEvenNumbers()
   {

      //given
      BiFunction<List<Integer>, Predicate<Integer>, List<Integer>> evenFinder = (list, even) -> {
         return list.stream().filter(even).collect(Collectors.toList());
      };

      //when
      List<Integer> evenNumList = evenFinder.apply(
         Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8),
         (num) -> num % 2 == 0
      );

      //verify
      MatcherAssert.assertThat(evenNumList, hasItems(2, 4, 6, 8));
   }

12/11/2018

[Java8] UnaryOperator Functional Interface

Unary operators need only one operand to perform the task or operation.

From Java definition

Represents an operation on single operand that produces a result of the same type as its operand. This is a specialization of Function for the case where the operand the result are of the same type.

Here are some test cases.

   @Test
   public void testUnaryOperator()
   {
      //when
      UnaryOperator<Integer> increment = (n) -> ++n;
      //verify
      Assertions.assertEquals(Integer.valueOf(2), increment.apply(1));

   }

12/10/2018

[Java8] Predicate Functional Interface

Definition of Predicate

  • a : something that is affirmed or denied of the subject in a proposition in logic
  • b : a term designating a property or relation

From java definition

Represents a predicate (boolean-valued function) of one argument.

Here are some test cases.
Evaluates this predicate on the given argument.

   public void testPredicateTest()
   {
      //given
      Predicate<Integer> isEven = (num) -> num % 2 == 0;
      //verify
      Assertions.assertTrue(isEven.test(4));
      Assertions.assertTrue(isEven.test(0));
   }

A composed predicate that represents a short-circuiting logical AND of this predicate and another.

   public void testPredicateTestAnd()
   {
      //given
      Predicate<Integer> isEven = (num) -> num % 2 == 0;
      Predicate<Integer> isEvenAndGreater100 = isEven.and((num) -> num > 100);
      //verify
      Assertions.assertTrue(isEvenAndGreater100.test(102));
      Assertions.assertFalse(isEvenAndGreater100.test(101));
      Assertions.assertFalse(isEvenAndGreater100.test(3));
   }

A composed predicate that represents a short-circuiting logical OR of this predicate and another.

   public void testPredicateTestOr()
   {
      //given
      Predicate<Integer> isEven = (num) -> num % 2 == 0;
      Predicate<Integer> isEvenOrGreater100 = isEven.or((num) -> num > 100);
      //verify
      Assertions.assertTrue(isEvenOrGreater100.test(102));
      Assertions.assertTrue(isEvenOrGreater100.test(101));
      Assertions.assertFalse(isEvenOrGreater100.test(3));

   }
   

A predicate that tests if two arguments are equal according to {@link Objects#equals(Object, Object)}.

   public void testPredicateIsEqual()
   {
      Assertions.assertTrue(Predicate.isEqual(20).test(20));
   }

12/09/2018

[Java8] Supplier Functional Interface

From wikipedia

  • Manufacturer, uses tools and labour to make things for sale
    • Processor (manufacturing), converts a product from one form to another
  • Wholesaler, sells goods or merchandise to retailers
  • Merchant, a professional dealing with trade

From java definition

Represents a supplier of results. There is no requirement that a new or distinct result be returned each time the supplier is invoked.

Here are some test cases.
Gets a result.

   @Test
   public void testGetCurrentDate()
   {
      //when
      Supplier<LocalDateTime> dateTimeSupplier = () -> LocalDateTime.now();

      //verify
      Assertions.assertNotNull(dateTimeSupplier.get());
   }

12/07/2018

[Java8] Function interface

Function interface has an abstract method "apply" which take argument of type T and must returns a result of type R.

Java definition

Represents a function that accepts one argument and produces a result.

public interface Function<T, R> {
    R apply(T t);
    ...
}

Here are some test cases.
Applies this function to the given argument.

    @Test
   public void testFuncApply()
   {
      Function<Integer, Integer> sqrt = (num) -> num * num;
      Assertions.assertEquals(Integer.valueOf(100), sqrt.apply(10));
   }

A composed function that first applies the function to its input, and then applies this to the result.

 @Test
   public void testFuncCompose()
   {
      //given
      Function<Integer, Integer> sqrt = (num) -> num * num;
      Function<String, Integer> input = sqrt.compose(((s) -> Integer.parseInt(s)));
      //when
      Integer result = input.apply("9");
      //verify
      Assertions.assertEquals(Integer.valueOf(81), result);
   }

A composed function that first applies this function to its input and the applies the function to the result.

   public void testFuncAndThen()
   {
      //given
      Function<Integer, Integer> sqrt = (num) -> num * num;
      Function<Integer, Integer> times = sqrt.andThen((num) -> num * num);
      Function<String, Integer> input = times.compose(((s) -> Integer.parseInt(s)));

      //when
      Integer result = input.apply("10");

      //verify
      Assertions.assertEquals(Integer.valueOf(10000), result);
   }

A function that always returns its input argument.

   @Test
   public void testIdentity()
   {
      //given
      Map<String, String> result =
         Arrays.asList("a", "b", "c")
            .stream()
            .collect(Collectors.toMap(Function.identity(), str -> str));
      //verify
      Assertions.assertTrue(result.size() == 3);
      Assertions.assertEquals(result.get("a"), "a");
      Assertions.assertEquals(result.get("b"), "b");
      Assertions.assertEquals(result.get("c"), "c");
   }

[Java8] Consumer Functional Interface

From wikipedia

A consumer is a person or organization that use economic services or commodities.

The consumer is the one who pays something to consume goods and services produced. As such, consumers play a vital role in the economic system of a nation. Without consumer demand, producers would lack one of the key motivations to produce: to sell to consumers. The consumer also forms part of the chain of distribution.

From Java definition

Represent an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, is expected to operate via side-effects.

Its main functional name is "accept", but why not call "consume" method. Does it mean consumer only accepts the input argument to consume?

Here are some test cases.
Performs this operation on the given argument.

  @Test
   public void testConsumerAccept()
   {
      //given
      List<String> names = new ArrayList();
      Consumer<String> addStudent = (name) -> names.add(name);
      //when
      addStudent.accept("chris");
      //verify
      Assertions.assertEquals("chris", names.get(0));
   }

A composed consumer that performs, in sequence, this operation followed by the code after operation

   public void testConsumerAcceptAndThenPrint()
   {
      //given
      List<String> names = new ArrayList();
      Consumer<String> addStudent = (name) -> names.add(name);
      Consumer<String> printStudentAfterAdding = addStudent.andThen(name -> System.out.println("added " + name));
      //when
      printStudentAfterAdding.accept("chris");
      //verify
      Assertions.assertEquals("chris", names.get(0));
   }

11/16/2018

Retry Design

Sometimes, Network is inherently unreliable. Connections will occasionally time out or be dropped. For some reasons, we still want to try to establish a connection to a remote endpoint which went down.

There is straightforward answer which wrote down below code to resolve it.

      try
      {
          this.conn = connect();
      }
      catch (Exception e)
      {
         for (int i = 0; i < maxAttempts; i++)
         {
            try { Thread.sleep(1000); } catch (InterruptedException e) {};
            this.conn = connect();
         }
      }

But the solution is difficult to maintain and a lack of flexibility. If we are using java8, this may change below to more be useful.

public static <T> Object retry(Supplier<T> function, int retryCount) throws Exception
   {
      while (0 < retryCount)
      {
         try
         {
            return function.get();
         }
         catch (Exception e)
         {
            if ((retryCount--) == 0)
               throw e;
         }
      }
      return null;
   }
   

Based on above two solutions, we still try to add extra code into connection logic and the unnecessary design. I think there's much better to use if you are using spring or AOP concept.

 @Retryable(maxAttempts = 3, backoff = @Backoff(delay = 500))
 public void establishConnection() {
    this.connection = newConnection();
 } 

Code is simply and easy to use.

Reference

spring-retry

11/01/2018

tldr

tldr is a small tool to help you cannot always remember the arguments to many commands as like me. TL;DR originates for "Too long; Didn't Read" in Internal Slang, where it is used to indicate that a long text has been skipped...

We like simplified man pages focused on practical example like below:

➜  ~ tldr lsof
Local data is older than two weeks, use --update to update it.


lsof

Lists open files and the corresponding processes.
Note: Root privileges (or sudo) is required to list files opened by others.

- Find the processes that have a given file open:
    lsof path/to/file

- Find the process that opened a local internet port:
    lsof -i :port

- Only output the process ID (PID):
    lsof -t path/to/file

- List files opened by the given user:
    lsof -u username

- List files opened by the given command or process:
    lsof -c process_or_command_name

- List files opened by a specific process, given its PID:
    lsof -p PID

- List open files in a directory:
    lsof +D path/to/directory

keep it simple, stupid.

tldr in alfred

Really enjoy this plugin in alfred.

https://github.com/cs1707/tldr-alfred

tldr github

https://github.com/tldr-pages/tldr

10/27/2018

sift

I like sift tool which is best than most other grep tools, to search the huge log and code base.

sift also is easy customizations to default ignore case as below.

An example config file: ~/.sift.conf

{
      "BinarySkip": true,
      "Git": true,
      "GroupByFile": true,
      "IgnoreCase": true
  }

Performance report

https://sift-tool.org/performance

Usage

https://sift-tool.org/samples

9/14/2018

Using curl to test port connectivity

It's often necessary to troubleshoot port connectivity as common env, but not found telnet.

curl -v telnet://target ip address:desired port number

curl -v telnet://dragon1:22
* Rebuilt URL to: telnet://dragon1:22/
* Trying 192.168.3.31...
* TCP_NODELAY set
* Connected to dragon1 (192.168.3.31) port 22 (#0)
SSH-2.0-Sun_SSH_1.1.4

4/10/2018

Generate Cron Expression in SOP

Sometimes, the cron expression is difficult to generate while you want to resolve urgent things. Let us SOP to generate cron expression.

Here are two links to easily generate cron expression.

  1. http://www.cronmaker.com/
  2. Cron Expression Generator & Explainer - Quartz

1/23/2018

Building Software

Based on Kent Beck describes three activities in building software:

  1. First make it work. (make business or money first)
  2. Then make it right. (refactor code ...you and others can understand it as needs change)
  3. Then make it fast. (refactor code for "needed" performance, don't do this first)