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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

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

Join 676 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
  • 224,456 hits
IndiBlogger
malliktalksjava.wordpress.c...
70/100
All tags
AngularJS Apache Cassandra Arrays in Java Cassandra Cassandra Database Cassandra examples client stubs creating a java web service creating a web service using java difference between interface and abstract class Differences between SOAP and RESTfull webservices Display div as Overlay using JQuery download the spring basic application File directory Generating webservice client stubs Hibernate hibernate exceptions How to display over using JQuery how to generated web service client stubs in STS How to implement Spring basic application how to write singleton design pattern in java interface in java Java Java Arrays Java Example Programs Java examples Java interview questions java programs java project Java sample Programs Java Script JavaScript JavaServer Faces Java Sorting alogorithms Java Tutorials javatutorials Java Web services JDBC open shift openshift Overlay implementation using JQuery Overlay in JQuery POI API POI Examples public class public static void main Redhat OpenShift representational state transfer Restfull webservices sample programs in java Service-oriented architecture Singleton design pattern in java SOAP SOAP Webservices software Spring Framework Spring Interview Questions Spring MVC Spring MVC Example program Spring MVC sample Program Spring Sample Programs Spring Tutorials Struts technology Top Java Interview questions w3c dom Web service web service client Web Service Description Language webservices Web services writing singleton design pattern in Java WSDL Xml xml parsers
%d bloggers like this: