Avoid nested loops using Collection Framework in Java


It is very important to have high performance for any software implemented in any programming language. And, as per truth loops plays major role in building the high performance applications. In this post, I have tried to explain how to avoid the loops using collection framework in Java.

Below are the two examples in Java programs to understand how the performance has increased using the collection framework.

1.UsingNesteadLoops.java:

package in.javatutorials;

/**
* Finds out the Duplicates is String Array using Nested Loops.
*
* @author JavaTutorials
* @since version 1.0
*/
public class UsingNesteadLoops {

/**
* Declare a String Array
*/
private static String[] strArray = { “Cat”, “Dog”, “Tiger”, “Lion”, “Lion” };

/**
* @param args
*/
public static void main(String[] args) {
isThereDuplicateUsingLoops(strArray);

}

/**
* Iterates the String array and find out the duplicates in Array
*
* @param strArray
* Array of values to find 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 observe the above lines of code, it will be looped 20 times to find out the duplicates in the string array which has the length of 5. The number of loops will be increased exponentially when the length of the array increases periodically, hence the performance is decreased. This kind of programs are not suggestible to use for high performanced applications.

2.AvoidNesteadLoopsUsingCollections.java:

package in.javatutorials;

import java.util.HashSet;
import java.util.Set;

/**
* Finds out the Duplicates is String Array using Collection Framework.
*
* @author JavaTutorials
* @since version 1.0
*/
public class AvoidNesteadLoopsUsingCollections {

/**
* Declare a String Array
*/
private static String[] strArray = { “Cat”, “Dog”, “Tiger”, “Lion”, “Lion” };

/**
* @param args
*/
public static void main(String[] args) {
isThereDuplicateUsingSet(strArray);

}

/**
* Iterates the String array and find out the duplicates in Array
*
* @param strArray
* Array of values to find 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”);
}

}

This program takes only 5 loops to identify the duplicates in the same array.

And, the approach using Set 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. Hence the performance increased.

 

Other Useful links:

Replace special characters in a String using java

How to convert an array to comma separated string in java

Convert Array to Vector in Java

Singleton Design pattern in JAVA

Replace special characters in a String using java

Advertisements
About

I born in Good cultural place called India. My family is traditional family. We fallow all Indian traditions.

Tagged with: , , , , , , , , , , ,
Posted in JAVA
2 comments on “Avoid nested loops using Collection Framework in Java
  1. […] Avoid nested loops using Collection Framework in Java […]

  2. […] Avoid nested loops using Collection Framework in Java […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 678 other followers

Calendar
June 2013
M T W T F S S
« Apr   Jul »
 12
3456789
10111213141516
17181920212223
24252627282930
Mallikarjun Gunda

This is Mallikarjun Gunda, I am working as a software professional. Blogging is my Passion. This blog contains the posts on Java related technologies and programming languages. I am happy to share my knowledge through the blogs.

Blog Stats
  • 271,322 hits
IndiBlogger
malliktalksjava.wordpress.c...
70/100
%d bloggers like this: