High performance is essential for any software implemented in any programming language. And, loops plays major role in this regard. This post explains how to avoid the loops using Java’s Collection framework.
Below are the two Java programs to understand how the performance could be increased using the Collection framework.
Using nested loops
package in.javatutorials; /** * Finds out the Duplicates is String Array using Nested Loops. */ public class UsingNesteadLoops { private static String[] strArray = { "Cat", "Dog", "Tiger", "Lion", "Lion" }; public static void main(String[] args) { isThereDuplicateUsingLoops(strArray); } /** * Iterates the String array and finds out the duplicates */ public static void isThereDuplicateUsingLoops(String[] strArray) { boolean duplicateFound = false; int loopCounter = 0; for (int i = 0; i < strArray.length; i++) { String str = strArray[i]; int countDuplicate = 0; for (int j = 0; j < strArray.length; j++) { String str2 = strArray[j]; if (str.equalsIgnoreCase(str2)) { countDuplicate++; } if (countDuplicate > 1) { duplicateFound = true; System.out.println("Duplicates Found for " + str); } loopCounter++; }// end of inner nested for loop if (duplicateFound) { break; } }// end of outer for loop System.out.println("Looped " + loopCounter + " times to find the result"); } }
If we run the above program, it will be looped 20 times to find out the duplicates in the string array which has the length of 5. Number of loops increases exponentially depending on size of array, hence the performance takes a hit. These are not acceptable to use in applications which require high performance.
Without using nested loops
package in.javatutorials; import java.util.HashSet; import java.util.Set; /** * Finds out the Duplicates is String Array using Collection. */ public class AvoidNesteadLoopsUsingCollections { private static String[] strArray = { "Cat", "Dog", "Tiger", "Lion", "Lion" }; public static void main(String[] args) { isThereDuplicateUsingSet(strArray); } /** * Iterates the String array and finds out the duplicates */ public static void isThereDuplicateUsingSet(String[] strArray) { boolean duplicateFound = false; int loopCounter = 0; Set setValues = new HashSet(); for (int i = 0; i < strArray.length; i++) { String str = strArray[i]; if(setValues.contains(str)){ duplicateFound = true; System.out.println("Duplicates Found for " + str); } setValues.add(str); loopCounter++; if (duplicateFound) { break; } }// end of for loop System.out.println("Looped " + loopCounter + " times to find the result"); } }
- Above approach takes only 5 loops to identify the duplicates in the same array.
- It is more readable , easier to maintain and performs better.
- If you have an array with 1000 items, then nested loops will loop through 999000 times and utilizing a collection will loop through only 1000 times.
Other Useful links:
2 thoughts on “Avoid nested loops using Collection Framework in Java”