2017  Kodetalk | Feedback | Privacy Policy | Terms | About

One liners in java

How about a line of java code will solve big problems like:

1: A line of java code will that will take a list of elements and returns a new list containing the same elements in the same order by removing duplicate element. For example we can say a list contains element/names like "Sandip, Deb, Deb, Sandip, Sandip, Tauseef, Deb, Sekhar" and the java one liner will give the final result as "Sandip, Deb, Tauseef, Sekhar".

To achive this result in java we should remember some basics of java class library like Set. Now we know that set removes duplicate elements from if we try to add duplicate. At the end Set gives all the unique elements from the elements we have added to set. And to get the data in the order the way we have added can be done using the algorithm of linkedlist. Now in collection package of java we have a class called LinkedHashSet which is going to give the result we are expecting.
For example:

return new ArrayList<E>(new LinkedHashset<E>(listOf));

Here listOf is the list which contains the values "Sadip, Deb, Gaurav, Deb, Sandip, Sandip, Gaurav, Tauseef, Deb, Sekhar".
And after return we will get a new list which will contain values "Sandip, Deb, Gaurav, Tauseef, Sekhar"

2: There could be a requirement like we have a string containing zero or more token separated by comma and return an array of string representing the tokens in the order in the input string. For example "i am surprised that, with expression, language this problem, could solve.". And after the process you will get the result as 4 element array string like "i am surprised that", "with expression", "language this problem", "could solve.".

return string.split(",s*");

Here string the variable which is holding the input string.

3: We basically come into situation that we have multidimensional array of values where we are not sure what is the dimension depth and we want to print the values of the array for debugging purpose. So solve that type of problem in java we have a really nice method which we can directly use for example :


If you pass the array to this method will print all values for you.

4: How about we have 2 int value and we want to check that the 1st int value contains more bits set than the second in 2"s complement binary representation.

return Integer.bitCount(int1) > Integer.bitCount(int2)

This will give result as true or false that the 1st int value have more bits set than the second.

In conclusion, i will say knowing the library will save lots of time of developers.