Automation Using Selenium Webdriver

Wednesday, 14 December 2016

Java – Remove Duplicate Number from Array

package JavaPrograms;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RemoveduplicateArray {
//
//  Remove duplicate entries from an array of long integers
//
//
public static void main(String[] args)
{
//
// A long integer array with some duplicated values
//
long [] longArray = { 11,0, 11, 22, 44, 55, 66, 77, 88, 0, 99, 77, 66, 42, 55, 66, 99, 11};
System.out.println("Original array size = " + longArray.length);
System.out.println("Original array            : " +
Arrays.toString(longArray));
//
// Want to let Java convert the array to a Set, since
// the Set object won't have duplicate entries.
//
// But first...
//
// Since the Set constructor needs a List (not an array),
// "convert" the array to a List.
//
List<Long> longList = new ArrayList<Long>();
for (int i = 0; i < longArray.length; i++)
{
longList.add(longArray[i]);
}
// Now, instantiate a Set with its constructor that has a List argument
Set <Long> longSet = new HashSet<Long>(longList);
//
// Create an array of Long objects and use Set.toArray()
// to "convert" the Set to the array.
Long[] resultNoDups = new Long[longSet.size()];
longSet.toArray(resultNoDups);
// Finally, if we want an array of long ints rather
// than an array of Long objects, create the array
// and copy the values
long [] finalArray = new long[resultNoDups.length];
for (int i = 0; i < resultNoDups.length; i++) {
finalArray[i] = resultNoDups[i];
}
// Taa-daa
System.out.println("After removing duplicates : " +
Arrays.toString(finalArray));
System.out.println("Result array size = " + finalArray.length);
System.out.println();
               }
}

No comments:

Post a Comment