3 Examples to Loop Through a List in Java 8

3 ways to Loop through a List in Java
There are multiple ways to traverse or loop through a List in Java e.g. by using an Iterator , by using an enhanced for loop of Java 5, and not the forEach() method of Java 8. Given a List is an index based collection, if you know the index you can retrieve an object from List and because of this you can also use traditional for loop which keeps count for iterating List. Now the question is whether should you use the Iterator or enhanced for loop, or the forEach() method of Java 8 for looping over List in Java. Well, it depends on what you are doing with the object, if you need to remove some objects from List than iterating using Iterator is best choice to avoid ConcurrentModificationExceptionbut if you are not removing any element and just doing some operation with each element than enhanced for loop is much cleaner ways to do that. 

Java Program to Perform Binary Search in Array without Recursion

The binary search algorithm is used to search an element in the sorted array. It's faster than linear search and improves performance from O(n) to O(logN) for searching an element in the array. In order to perform the binary search, you need a sorted array, so you can either ask the user to enter array in sorted order or you should sort the array before performing the binary search. In this article, we will write a Java program which will take input from the user, both array and the number to be searched and then perform a binary search to find that number in given array. We'll not use the Collections.binarySearch() method instead we'll write our own because it's a programming exercise to test one's coding skill. In order to implement binary search, you must first know how binary search works? If you don't know the algorithm you cannot code it. So, let's first revise the binary search algorithm itself.

keySet() vs entrySet vs values() Example in Java Map

The java.util.Map interface provides three methods keySet(), entrySet() and values() to retrieve all keys, entries (a key-value pair), and values. Since these methods directly come from the Map interface, you can use it with any of the Map implementation class e.g. HashMap, TreeMap, LinkedHashMap, Hashtable, ConcurrentHashMap, and even with specialized Map implementations like EnumMap, WeakHashMapand IdentityHashMap. In order to become a good Java developer, it's important to understand and remember key classes Java API e.g. Java's Collection framework. In this article, we will not only learn the difference between keySet(), entrySet() and values() methods, but also learn how to use them in Java program by looking at a simple example.