Java: Zip collections using Guava library

In this post, we are going to see how to zip two lists in Java.

For example, we have two lists such as first names and last names and we want to zip these two collections and create another list that contains both first name and last name. Something like below.

firstNames -> [“John”, “Peter”]

lastNames -> [“Glassman”, “Robertson”]

Output -> [“John Glassman”, “Peter Robertson”]

As we all know that we don’t have a direct way to do this in Java but Guava utility provides a method to do this.

You can refer the documentation here:

Lets write a code with this method to zip these two lists.


import java.util.ArrayList;
import java.util.List;

public class JavaZipFunction {

    public static void main(String[] args) {

        List<String> firstNames = new ArrayList<String>() {{

        List<String> lastNames = new ArrayList<String>() {{

        List<String> names =,
                                         (firstName, lastName) -> (firstName + " " + lastName)



The output will look like below.

ScalaTest: FunSpec and FunSuite

ScalaTest supports different types of testing styles, each designed to address a particular set of needs.

Refer to this link to know more about various testing styles.

In this post, we are going to talk about FunSpec and FunSuite and how to write tests using these styles.

Assume that we have scala object Operation which has a method called divide and it’s used to perform division operation.



Now, Let’s write a test for this scala class with different styles.

For teams coming from xUnit, FunSuite feels comfortable and familiar while still giving some of the benefits of BDD: FunSuite makes it easy to write descriptive test names, natural to write focused tests, and generates specification-like output that can facilitate communication among stakeholders.

Below is the test class which uses FunSuite style.


For teams coming from Ruby’s RSpec tool, FunSpec will feel very familiar; More generally, for any team that prefers BDD, FunSpec’s nesting and gentle guide to structuring text (with describe and it) provides an excellent general-purpose choice for writing specification-style tests.

Below is the test class which uses FunSpec style.


Arrange Act Assert Pattern

It’s a pattern for arranging and formatting unit test methods. The main benefit of this pattern is that it clearly separates what is being tested from setup and verification steps.

The below are the steps defined in this pattern.

1. Arrange all necessary preconditions and inputs.
2. Act on the object or method under test.
3. Assert that the expected results have occurred.

Example unit test method is given below.

 public void testAdd() {
    int a = 10;
    int b = 10;
    int c = Calculate.add(a, b);
    assertEquals(20, c);

The above method is used for testing the “add” method defined in In the first 2 lines, the input parameters(Arrange) are defined and in the 3rd line, the add method is getting called with the given input parameters(Act) and in the 4th line, the result value is getting verified(Assert).

Scala Either Monad

Either is one of the most useful monads in Scala. Its similar like Scala Option.
In this post, we are going to see how we can use this with an example.


  • Its an abstract class extends Product.
  • Its an alternative to Option Monad.
  • An instance of Either is either an instance of scala.util.Left or scala.util.Right.
  • Left is used for failure and Right is used for success.
  • Mainly used in error handling.
  • The returned value is either an error or valid value.

Assume that we have a function and want to do some operation before doing that we want to do some validation and throw an error if the validation fails otherwise perform the operation and return the value.

Lets refer the below example to know how to do that with “Either” Monad.


The output is given below,


In the above example, we have a function “divide” which takes two values and perform divide operation and then return a result.

If the divisor is zero, then it will throw an error. So we first validate it and if the divisor is zero, then we will wrap the error in a case class “CalculationError” and return an instance of Left which represents an error.

If there is no error, then we will perform the divide operation and return the result as an instance of “Right” which represents success scenario

Scala String Interpolation

String interpolation is a feature of Scala and it enables us to embed variable references directly in processed string literals.

We have three kinds of Scala String interpolators. Let’s see them one by one.

s String interpolator
f String interpolator
raw String interpolator

s String interpolator:

When we prepend ‘s’ to any string, we can directly use variable in it with the use of $ character. But that variable should be in scope.

  val name = "John"
  println(s"My Name is $name")  // My Name is John

f string  interpolator
When we prepend ‘f’ to a processed string literal which allows  the creation of formatted strings, Its similar to “printf” in Java.

val height = 1.9d
val name = "John"
println(f"$name%s is $height%.2f meters tall")  // John is 1.90 meters tall

raw interpolator
It’s similar to ‘s’ interpolator except that it performs no escaping of literals within the string.

Refer the below example,

val name="John"
println(s"My name is \n$name")  //My name is

Here the s interpolator, replaced the character \n with a return character.  The “raw” interpolator will not do that.

val name="John"
println(raw"My name is \n$name") //My name is \n John

Scala App Trait

Scala contains a trait called “App” and its used to turn objects into executable programs.

We do not need to explicitly define “main” method in a Scala object, instead the whole class body becomes the main method.

Refer the below example,


In the above code, we define an object “ScalaMain” and in the body of that object, we define a function “add” for adding two numbers. The whole code section becomes the main method.

Java 9: Immutable List, Set and Map

Java 9  provides a convenient way to create an immutable collections such as List, Set and Map. In this post, we are going to see that with few examples.

Prior to Java 9, To create an immutable collections, we have to follow the below approach. It works fine but its verbose.


Now, in Java 9, we can easily, create an immutable list with the List.of() method.

The List.of method returns an instance of “java.util.ImmutableCollections.ListN” [extends AbstractImmutableList]. As this class extends AbstractImmutableList, the returned list is an immutable list, so trying to update it, will throw UnsupportedOperationException.


We can follow the same way for creating an immutable Set and Map. Refer the below examples.

The Set.of method returns an instance of “java.util.ImmutableCollections.SetN” [extends AbstractImmutableSet]. Its immutable so trying to update it, will throw UnsupportedOperationException.

The Map.of method returns an instance of “java.util.ImmutableCollections.MapN” [extends AbstractImmutableMap]. Its immutable so trying to update it, will throw UnsupportedOperationException.



Scala Case Class

Scala class classes are like regular classes but with a few differences.  Those are given below.


  • When we create a case class, it also creates a companion object implicitly with apply and unapply methods.
  • By default, Case classes are serializable.
  • Case class instances can be created without using the new keyword.  By default, the apply method of case class companion object will be called and it creates an instance of case classes.
  • Suitable for modeling immutable data.
  • Case classes automatically define the toString, equals and hashCode methods.
  • Case class constructor parameters are public val’s. So we can’t modify the values once it’s assigned. Because those parameters are immutable or constant.
  • Case classes automatically define the getter methods for constructor arguments.
  • It can be used in Pattern Matching operation.
  • It contains an implicit ‘copy’ which is used for creating a copy of a case class instance. We can also optionally change the constructor arguments.
  • Scala case classes can’t be extended by other case class.


Scala val, var and def

In this post, we are going to see the difference between var, val and def keywords of Scala.

Var –  If you want to create a mutable variable in Scala, then you have to use var keyword. For example, you want to create a variable and the value of that variable will be changed, then you need to use var keyword to define a mutable variable.

Val –  If you want  to create an immutable variable, then you have to use val keyword. Its like creating a constant value so once the value is assigned to a variable, then its never going to change. Even if you do, then you would get a compilation error.

def – To define a function, then you have to use this keyword.

Refer the below example, to know how to use these keywords.

val keyword usage:

In the below example, we use the ‘def’ keyword to define a function. We create a variable with ‘val’ keyword and then try to modify the value once its assigned. So when you do that, then you would get a compilation error.


var keyword usage:


Java: Double brace initialization

“Double Brace Initialization” is a hidden feature of Java and used for initializing collection classes such as ArrayList, HashSet, and HashMap.

Even though the code looks more readable with this feature, be aware that it can cause memory issues.

In this post, we are going to see how we can use this with an example.


The output is given below,

{1=data1, 2=data2}

In the above code, dataMap is a HashMap which contains a key/value and double brace block contains the code to initialize this HashMap.

When a code contains a double brace block, then the compiler would generate an anonymous inner class which extends that collection class.

Let’s verify this with the above example. After compilation, I checked the target folder and it contains the below class files.


I opened up the DoubleBraceInitTester$1.class which is an anonymous inner class and it looks like below. So the compiler copied all the initialization code into the constructor of this class.