Sunday, February 15, 2015
Saturday, February 7, 2015
HashMap is not synchronized, which means you cannot use it on multi-threaded Java program without external synchronization. In another word, if you share one instance of HashMap between multiple thread, each is either adding, removing or updating entries then it's possible that HashMap loss its structure and not behave as expected. If you have read my earlier article about HashMap, you know that during re-sizing its possible that HashMap exposed to multiple thread, may end up in infinite loop. In order to avoid this, usually one HashMap instance is used by one thread, sharing of HashMap instance is not allowed, but if you have to share HashMap and there is no option to avoid that, you can always synchronize HashMap in Java. Ofcourse this will affect the performance and probably reduce the speed of HashMap as synchronized method is always slower than non-synchronized one. In this tutorial, we will learn how we can synchornize HashMap in Java.
Saturday, January 31, 2015
Map is a well known functional programming concept which is incorporated into Java 8. Map is a function defined in java.util.stream.Streams class, which is used to transform each element of stream. Because of this property you can use Map in Java 8 to transform a Collection, List, Set or Map. For example, if you have a list of String and you want to convert all of them into upper case, how will you do this? Prior to Java 8, there is no function to do this. You had to iterate through List using a for loop or foreach loop and transform each element. In Java 8, you get stream, which allow you to apply many functional programming operator like map, reduce and filter. By using Map function you can apply any function to every element of Collection. It can be any predefined function or a user defined function. You not only can use lambda expression but also you can also use method references. Some examples of Map in Java 8 is to convert a list of integers and then square of each number. Map function is also an intermediate operation and it return a stream of transformed element. Stream API also provides methods like mapToDouble(), mapToInt(), and mapToLong() which returns DoubleStream, IntStream and LongStream, which are specialized stream for double, int and long data types. You can collect the result of transformation by using Collectors class, which provides several method to collect the result of transformation into List, Set or any Collection.