Avoid nested loops using Collection Framework in Java


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:

Convert Array to Vector in Java


package com.test;

import java.util.Arrays;
import java.util.Vector;

public class ArrayTest {

public static void main(String[] args) {
ArrayTest arrayTest = new ArrayTest();
arrayTest.arrayToVector();
}
public void arrayToVector() {

String[] arrayToConvert = { “jhony”, “peter”, “don” };

Vector<String> convertedVector = new Vector<String> Arrays.asList(arrayToConvert));

System.out.println(“11111 ” + convertedVector.get(0));

System.out.println(“3” + convertedVector.size());
}
}

How to convert an array to comma separated string in java


package com.test;

public class ArrayTest {

public static void main(String[] args) {
ArrayTest arrayTest = new ArrayTest();
arrayTest.arrayJoin();
}

public void arrayJoin() {

String[] arrayToJoin = { “John”, “Peter”, “Tom”, “Scott” };

StringBuilder joinedString = new StringBuilder();
String seperator = “,”;
//System.out.println(“Converting to String “+arrayToJoin.toString());;
for (String value : arrayToJoin) {
joinedString.append(value).append(seperator);
}

System.out.println(“Final Result …….. ” + joinedString);
}
}

How to Copy an Array into Another Array?


Contents of one array can be copied into another array by using the arraycopy() method of the System class in Java.

  • arraycopy() method accepts source array, source length, destination array and destination length.
  • Following program shows the use of arraycopy() method to copy the contents of one array to another.
package com.Test;

public class ArrayCopyTest{
 public static void main(String[] args){
    int[] src = new int[] {1, 2, 3, 4, 5};
    int[] dest = new int[src.length];
    System.arraycopy(src, 0, dest, 0, src.length);
    for (int i = 0; i < dest.length; i++){
       System.out.println(dest[i]);
    }
  }
}

How to check duplicated value in array


package com.test;

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

public class CheckDuplicate
{
	public static void main(String args[])
	{
		String [] sValue = new String[]{"a","b","c","d","","","e","a"};

		if(checkDuplicated_withNormal(sValue))
			System.out.println("Check Normal : Value duplicated! \n");
		if(checkDuplicated_withSet(sValue))
			System.out.println("Check Set : Value duplicated! \n");

	}

	//check duplicated value
	private static boolean checkDuplicated_withNormal(String[] sValueTemp)
	{
		for (int i = 0; i < sValueTemp.length; i++) {
			String sValueToCheck = sValueTemp[i];
			if(sValueToCheck==null || sValueToCheck.equals(""))continue; //empty ignore
			for (int j = 0; j < sValueTemp.length; j++) {
					if(i==j)continue; //same line ignore
					String sValueToCompare = sValueTemp[j];
					if (sValueToCheck.equals(sValueToCompare)){
							return true;
					}
			}

		}
		return false;

	}

	//check duplicated value
	private static boolean checkDuplicated_withSet(String[] sValueTemp)
	{
		Set<String> sValueSet = new HashSet<String>();
		for(String tempValueSet : sValueTemp)
		{
			if (sValueSet.contains(tempValueSet))
				return true;
			else
				if(!tempValueSet.equals(""))
					sValueSet.add(tempValueSet);
		}
		return fals