Java 8 Map Function Examples

The 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 the 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 the stream, which allows you to apply many functional programming operators like the 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 the lambda expression but also, you can also use method references.

How to Generate Random Number between 1 to 10 - Java Example

There are many ways to generate random numbers in Java e.g. Math.random() utility function, java.util.Random class or newly introduced ThreadLocalRandom and SecureRandom, added on JDK 1.7. Each has their own pros and cons but if your requirement is simple, you can generate random numbers in Java by using Math.random() method. This method returns a pseudorandom positive double value between 0.0 and 1.0, where 0.0 is inclusive and 1.0 is exclusive. It means Math.random() always return a number greater than or equal to 0.0 and less than 1.0. Internally it uses java.util.Random class. So when you first call this method, it creates an instance of Random class and caches it for future use. Any further call is a just equivalent of Random.nextDouble(). If your requirement is more sophisticated i.e. you need random numbers between a range or multiple threads needs to generate random number simultaneously, then you should look other random solution available in Java.

How To Convert Map to List in Java with Example

Before converting a Map to a List in Java,  we should be very clear about these data structures which are widely  used in Java. So let's begin with Map. What is Map? Map is an Interface in Java which store key and value object. It's Java representation of popular hash table data structure which allows you to search an existing element in O(1) time, at the same time also makes insertion and removal easier.  We use a key object to retrieve the value object by using hashing functionality provided by Map. As we have seen in how get method of HashMap works, In Java, equals() and hashcode() method are an integral part of storing and retrieving object from it. The map allows duplicate values but no duplicate keys. Map has its implementation in various classes like HashMap, ConcurrentHashMap, and TreeMap. The Map interface also provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings.

Second Highest Salary in MySQL and SQL Server - LeetCode Solution

Write a SQL query to get the second highest salary from the Employee table.

+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

For example, given the above Employee table, the second highest salary is 200. If there is no second highest salary, then the query should return NULL. You can write SQL query in any of your favorite database e.g. MySQL, Microsoft SQL Server or Oracle. You can also use database specific feature e.g. TOP, LIMIT or ROW_NUMBER to write SQL query, but you must also provide a generic solution which should work on all database. In fact, there are several ways to find second highest salary and you must know couple of them e.g. in MySQL without using LIMIT keyword, in SQL Server without using TOP and in Oracle without using RANK and ROWNUM. Once you solve the problem, Interviewer will most likely increase the difficulty level by either moving to Nth salary direction or taking away this buit-in utilities.

How to calculate Sum of Digits using Recursion in Java

This is the second part of our article to solve this coding interview question,  how to find the sum of digits of an integer number in Java. In the first part, we have solved this problem without using recursion i.e. by using a while loop and in this part, we will solve it by using recursion. It's good to know different approaches to solving the same problem, this will help you to do well on coding interviews. While finding a recursive algorithm, always search for a base case, which requires special handling. Once you find the base case, you can easily code the method by delegating rest of processing to the method itself, i.e. by using recursion.  In this problem, the base case is when the number becomes zero, at that time our program is complete and we return the sum of digits of given number. Another property of a recursive algorithm is that with each passing steps your program approaches to result and problems become shorter.

How to reverse ArrayList in Java with Example

You can reverse ArrayList in Java by using the reverse() method of java.util.Collections class. This is one of the many utility methods provided by the Collections class e.g. sort() method for sorting ArrayList. The Collections.reverse() method also accepts a List, so you not only can reverse ArrayList but also any other implementation of List interface e.g. LinkedList or Vector or even a custom implementation. This method has a time complexity of O(n) i.e. it runs on linear time because it uses ListIterator of given list.  It reverses the order of an element in specified list. By the way you cannot reverse an ArrayList using this method if the specified ArrayList or it's ListIterator doesn't support set() operation. It switches between two algorithms depending upon the size of List or if List implements RandomAccess interface e.g. ArrayList.

How to Sort HashMap in Java based on Keys and Values

HashMap is not meant to keep entries in sorted order, but if you have to sort HashMap based upon keys or values, you can do that in Java. Sorting HashMap on keys is quite easy, all you need to do is to create a TreeMap by copying entries from HashMap. TreeMap is an implementation of SortedMap and keeps keys in their natural order or a custom order specified by Comparator provided while creating TreeMap. This means you can process entries of HashMap in a sorted order but you cannot pass a HashMap containing mappings in a specific order, this is just not possible because HashMap doesn't guarantee any ordering. On other hand, sorting HashMap by values is rather complex because there is no direct method to support that operation. You need to write code for that. In order to sort HashMap by values you can first create a Comparator, which can compare two entries based on values. Then get the Set of entries from Map, convert Set to List and use Collections.sort(List) method to sort your list of entries by values by passing your customized value comparator. This is similar of how you sort an ArrayList in Java. Half of the job is done by now. Now create a new LinkedHashMap and add sorted entries into that. Since LinkedHashMap guarantees insertion order of mappings, you will finally have a Map where contents are sorted by values.