SysOutNull (bpfurtado) wrote,
SysOutNull
bpfurtado

Doing some compact code in Java 8

My good friend Rafael Naufal has posted a very interesting challenge which consists in comparing the expressiveness of different languages to a very single problem involving object containers, and as much as I can see that Java is the more verbose between his examples I could provide a more expressive version of the Java 8 solution:

   1 Map<String, List<String>> mapOfLists = new HashMap<>();
   2 mapOfLists.put("a", Arrays.asList("1", "2", "3"));
   3 mapOfLists.put("b", Arrays.asList("4", "5", "6"));
   4 mapOfLists.put("c", Arrays.asList("7"));
   5 
   6 class Pair {
   7     String key, val;
   8 
   9     public Pair(String key, String val) {
  10         this.key = key;
  11         this.val = val;
  12     }
  13 
  14     public String toString() {
  15         return String.format("[%s, %s]", key, val);
  16     }
  17 }
  18 
  19 List<Pair> pairs = new LinkedList<>();
  20 mapOfLists.forEach((k, list) -> list.forEach(e -> pairs.add(new Pair(k, e))));
  21 System.out.println(pairs)


The output is:

[[a, 1], [a, 2], [a, 3], [b, 4], [b, 5], [b, 6], [c, 7]]

The key issues are:

  1. Other languages can do the creation of the Map in pretty much a single line, Java could would be this 4 lines yes;

  2. In the absence of Tuples we must create a 'Pair' class (getting 10 more lines), although I consider the toString significantly improved;

Other than that the actual transformation (line 20 above) is just one line like in the other languages, which says a lot about Java, being statically typed and all (the comparison used Ruby and Groovy).

I also did not use the Java 8 enhanced APIs (particulary the Stream package), but it was also not necessary, but once I study it I can provide another code, being less compact or not.

I'll try to provide an example in both Kotlin and Scala in the future (I think both provide one-liners for class declarations and/or tuples).
Tags: closures, java8
Subscribe

  • Post a new comment

    Error

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 0 comments