Posts Tagged java

Converting a Map to a List in Java 8, Groovy and Ruby

Some days ago I was developing a task on a Gradle project and I faced with a situation where I had to convert a Map < String, List < String >> to List < Pair >, each pair containing the key and one element from the List<String>.

I decided to compare the solution in three different languages: Java 8 (using lambdas and the Streams API), Groovy and Ruby to see how concise and expressive they would be. Then, I created the Groovy code and it looked like this:

#!/usr/bin/env groovy

def map = ["a" : ["1", "2", "3"], "b" : ["4", "5", "6"], "c" : ["7"]]

println map.collectMany { key, values -> values.collect {value -> [key, value]}}

Running the above code, the result is below:

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

The Ruby version looked like this:

#!/usr/bin/env ruby

map = { "a" => ["1", "2", "3"], "b" => ["4", "5", "6"], "c" => ["7"] }

p map.collect {|key, values| values.map {|value| [key, value] } }.flatten(1)

The Ruby program generated the following output:

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

Below is the Java 8 version, using lambdas, Streams and the Collectors API:

        
        Map> values = new HashMap<>();
        values.put("a", Arrays.asList("1", "2", "3"));
        values.put("b", Arrays.asList("4", "5", "6"));
        values.put("c", Collections.singletonList("7"));

        final List result = values
                .entrySet()
                .stream()
                .collect(ArrayList::new,
                        (pairs, entry) -> pairs.addAll(entry
                                .getValue()
                                .stream()
                                .map(value -> new Pair(entry.getKey(), value))
                                .collect(Collectors.toList())),
                        List::addAll);

private static class Pair {

    private final String first;
    private final String second;

    public Pair(String first, String second) {
        this.first = first;
        this.second = second;
    }

    @Override
    public String toString() {
        return "Pair{first='" + first + "', second='" + second + "'}";
    }
}

Running the Java 8 version produced the following output:

[Pair{first='a', second='1'}, Pair{first='a', second='2'}, 
Pair{first='a', second='3'}, Pair{first='b', second='4'}, 
Pair{first='b', second='5'}, Pair{first='b', second='6'}, 
Pair{first='c', second='7'}]

The Groovy and Ruby version are very expressive and concise. Note the use of the collectMany method on the Groovy version and the use of the flatten method on the Ruby version to flatten the result list into a single list of pairs.
The Java 8 version made use of the collect method of the Stream API, to collect the results in a list of Pair instances, each one holding the key and value of each element from the List< String >.

What do you think about this comparison? Leave your comments here!

Tags: , , , , , , ,

When to use TestNG or JUnit

There is an interesting discussion between using TestNG or JUnit on Java projects at Javalobby. It’s very worth reading.

Tags: , , , ,

Configuration classes with Enums

As I mentioned on my previous post, an alternative implementation to create Singleton in Java is with Enum types.

Extending the idea, it is interesting to create classes which read configuration values from Properties files with Enum classes. Below is an example:

public enum Configuration {

    HOST("host"),
    PORT("port"),
    MAIL_SERVER("mailServer"),
    INPUT_DIRECTORY("inputDirectory"),
    OUTPUT_DIRECTORY("outputDirectory");

    private static Properties properties;
    static {
        properties = new Properties();
        try {
            properties.load(Configuration.class.getClassLoader().getResourceAsStream(
                "configuration.properties"));
        } catch (Exception e) {
            throw new RuntimeException("Error when loading configuration file", e);
        }
    }

    private String key;

    Configuration(String key) {
        this.key = key;
    }

    public String getKey() {
        return key;
    }

    public String getValue() {
        return properties.getProperty(key);
    }
}

Configuration classes which read values from properties files should be Singletons that are loaded once on the application startup time.

The Configuration values can be used this way:

System.out.println(Configuration.HOST.getValue());

This example shows that the key and value from properties are stored with Enum constants. They are type-safe, they can be easily accessed through code completion in your favourite IDE and they can take advantage of refactoring tools.

Tags: , , , ,

Singleton in Java with Enum types

Java 1.5 introduced the concept of Enum types. They are type-safe constants, which implements equals(), hashCode() and cannot be extended. Each constant can have attributes and override an abstract method created on each Enum class.

Although Singletons are not encouraged, the best way to create it is using Enum types. Here is an example:

public enum Singleton {
    INSTANCE;

    public void sayHello() {
	   System.out.println("Hello World!");
    }
}

And then you call it this way:

Singleton.INSTANCE.sayHello();

Using Enums to create Singletons brings the serialization mechanism already bundled in the Enum type. This technique is described on the Effective Java Second Edition book by Joshua Block.

Tags: , , , , ,

Java-Quiz: The Iterator Quiz

Danilo sent us an interesting Java-Quiz from the Java Specialists’ Newsletter created by Olivier Croisier. You have to insert your corrective code in place of the //FIXME comment, following these instructions:

  1. Do not modify his existing code, it’s Perfect (of course).
  2. The FIXME tag shows where you’re allowed to insert your corrective code
  3. He must be able to understand your solution when he comes back (so using Reflection is not an option).

Can you find a solution for it?

final List<String> list = new ArrayList() {{ 
      add("Hello"); 
}};
final Iterator<String> iterator = list.iterator();
System.out.println(iterator.next());
list.add("World");
// FIXME : work here while I'm sunbathing
System.out.println(iterator.next());

Later I’ll post my attempt to solve it.

Tags: , , ,

Eclipse Log4J template

My friend Bruno sent me an interesting tip on how to create a Log4J template at Eclipse. Just follow these steps:

  1. Go to Window > Preferences > Java > Editor > Templates
  2. Click New
  3. Write the string logger at the field Name (this name will be used to call the template)
  4. At the field Pattern, write the following:

    private static final Logger LOGGER = Logger.getLogger(${enclosing_type}.class);

  5. Click OK

The variable ${enclosing_type} refers to the enclosing type name. When you are ready, write down logger on the field class declaration to have a logger added to the class.

Tags: , , , ,

Using Hamcrest and JUnit

Lately I started using the core Hamcrest matchers bundled with the JUnit framework to create more readable unit tests.

Hamcrest matchers were created to improve the readability of unit testing code. It’s a framework which facilitates the creation of matcher objects to match rules specified in unit tests. Some examples will let it to be clearer:

   1 import static org.hamcrest.CoreMatchers.equalTo;
   2 import static org.hamcrest.CoreMatchers.is;
   3 import static org.junit.Assert.assertThat;
   4 
   5 @Test
   6 public void shouldBeTheSamePerson()
   7 {
   8     Person me = new Person( "Rafael" );
   9     Person theOther = new Person( "Rafael" );
  10     assertThat( me, is( theOther ) );
  11 }
  12 
  13 @Test
  14 public void shouldHaveFixedSizeNumbers()
  15 {
  16     List<Integer> numbers = Arrays.asList( 1, 2, 3, 4, 5 );
  17     assertThat( numbers.size(), is( equalTo( 5 ) ) );
  18 }

The first example checks if one Person object is equal to another using the Object equals method, which was overridden in the Person class. The is syntax defines a matcher which is a shorthand to is(equalTo(value)). The second one uses the is(equalTo(value)) matcher to check the size of an integer list of fixed size numbers. The assertThat method is used in conjunction with the is(equalTo(value)) matcher, which makes the test sentence very human readable.

An interesting thing is the possibility to create a custom matcher, like this one which tests if a given list only has even numbers:

   1 public class AreEvenNumbers extends TypeSafeMatcher<Collection<Integer>> {
   2 
   3     @Override
   4     public boolean matchesSafely(Collection<Integer> numbers) {
   5         for (Integer number : numbers) {
   6             if (number % 2 != 0) {
   7                 return false;
   8             }
   9         }
  10         return true;
  11     }
  12 
  13     @Override
  14     public void describeTo(Description description) {
  15         description.appendText("even numbers");
  16     }
  17 
  18     @Factory
  19     public static <T> Matcher<Collection<Integer>> evenNumbers() {
  20         return new AreEvenNumbers();
  21     }
  22 }

And below are two tests which uses the AreEvenNumbers custom matcher:

   1 import static org.hamcrest.CoreMatchers.is;
   2 import static org.junit.Assert.assertThat;
   3 import static br.com.rafael.hamcrest.AreEvenNumbers.evenNumbers;
   4 
   5 @Test
   6 public void shouldHaveOnlyEvenNumbers()
   7 {
   8     List<Integer> numbers = Arrays.asList( 2, 4, 6, 8, 10 );
   9     assertThat( numbers, is( evenNumbers() ) );
  10 }
  11 
  12 @Test
  13 public void shouldNotHaveOddNumbers()
  14 {
  15     List<Integer> numbers = Arrays.asList( 1, 2, 4, 6, 8, 10 );
  16     assertThat( numbers, not( evenNumbers() ) );
  17 }

These two tests use the static factory method evenNumbers to instantiate the matcher on the test code. Not the use of the not matcher on the shouldNotHaveOddNumbers test to assert that no odd numbers are present on the given list. All tests use the static import feature, which turns the test not clean and not cluttered with the class qualification.

I haven’t experienced the other common matchers on unit testing code, like the Beans, Collections and Number ones. I think they turn the tests more readable, clean and easy to change. And you? Have you ever used Hamcrest matcher? If you have other examples of using it, post them here!

Updated: Static imports were added to the testing code.

Tags: , , , , , ,

JDK7 Tackles Java Verbosity

Interesting article showing some changes on the Java platform to address its verbosity, but keeping code readability safe.
I liked the new Collection’s literals syntax to create lists, sets and maps:

List powersOf2 = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024};
Map ages = {"John" : 35, "Mary" : 28, "Steve" : 42};

Although it can be possible to use the DoubleBraceInitialization idiom to initialize collections in a more elegant way, this syntax is very terse and concise.

BTW, as I said before, Scala already has a syntactic sugar to create a literal Map:

val ages = Map("John" -> 35, "Mary" -> 28, "Steve" -> 42)

Maybe this change was taken into account considering the Scala collection literals implementation?

Tags: , , , , , , ,

A Brief History of Java and JDBC

From Javalobby, an interesting and short video showing the evolution of the Java platform since 1991.

Tags: , , ,

Using Scala to update LiveJournal tags – Part I

Some days ago I started to use the Scala programming language to update my Livejournal tags using its XML-RPC protocol reference. First I had to check if some tags of mine were entered wrong, so I’ve done this Scala program to list all of them:

   1:import org.apache.xmlrpc.client.XmlRpcClient;
   2:import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
   3:import org.apache.xmlrpc.client.XmlRpcCommonsTransportFactory;
   4:import java.net.URL;
   5:import java.util.Map
   6:import java.util.HashMap
   7:import scala.collection.immutable.TreeSet
   8:
   9:object LJListTag {
  10:     def main(args: Array[String]) {
  11:         val config = new XmlRpcClientConfigImpl()
  12:         config.setEnabledForExtensions(true);
  13:         config.setServerURL(new URL("http://www.livejournal.com/interface/xmlrpc"))
  14:         val client = new XmlRpcClient()
  15:         client.setConfig(config)
  16:         val params = new HashMap[String, String]
  17:         params.put("username", "user")
  18:         params.put("password", "password")
  19:         var paramsToServer = new Array[Object](1)
  20:         paramsToServer(0) = params
  21:         val results = client.execute("LJ.XMLRPC.getusertags", paramsToServer).asInstanceOf[Map[String, String]];
  22:         printEachTag(results)
  23:     }
  24:    
  25:     def printEachTag(results: Map[String, String]) {
  26:        var allTags = new TreeSet[String]
  27:        val iterator = results.values().iterator()
  28:           while(iterator.hasNext()) {
  29:             val resultFromRPCData = iterator.next().asInstanceOf[Array[Any]]
  30:             resultFromRPCData.foreach(singleResult => allTags += extractTag(singleResult))
  31:           }
  32:        allTags.foreach(tag => println(tag))
  33:     }
  34:    
  35:    def extractTag(singleResult: Any): String = {
  36:        val tag = singleResult.asInstanceOf[HashMap[String, String]]
  37:        return tag.get("name")
  38:    }
  39:}

Just fill your user and password to have all of your LiveJournal tags printed on the standard output. The experience was so amazing, since you can use all the Java libraries (Scala is fully interoperable with Java and runs on top of the JVM). I used a TreeSet because I wanted print my tags sorted according its alphabetical order. I’m continuously studying Scala and its API, so the code above doesn’t use any advanced Scala constructs. If you have any suggestion about the code or how to use better the Scala constructs, post your comments here. It will be all appreciated.

Tags: , , , , ,