Strings and Arrays

This Java program is used to find duplicate characters in string.
public class DuplStr { public static void main(String argu[]) { String str = "w3schools"; int cnt = 0; char[] inp = str.toCharArray(); System.out.println("Duplicate Characters are:"); for (int i = 0; i < str.length(); i++) { for (int j = i + 1; j < str.length(); j++) { if (inp[i] == inp[j]) { System.out.println(inp[j]); cnt++; break; } } } } }


Duplicate Characters are: s o

Explanation:

Here in this program, a Java class name DuplStr is declared which is having the main() method. All Java program needs one main() function from where it starts executing program.  Inside the main(), the String type variable name str is declared and initialized with string w3schools. Next an integer type variable cnt is declared and initialized with value 0. This cnt will count the number of character-duplication found in the given string.

The statement: char inp [] = str.toCharArray(); is used to convert the given string

to character array with the name inp using the predefined method toCharArray(). The System.out.println is used to display the message "Duplicate Characters are as given below:". Now the for loop is implemented which will iterate from zero till string length. Another nested for loop has to be implemented which will count from i+1 till length of string.
Inside this two nested structure for loops, you have to use an if condition which will check whether inp[i] is equal to inp[j] or not. If the condition becomes true prints inp[j] using System.out.println() with s single incrementation of variable cnt and then break statement will be encountered which will move the execution out of the loop.
Program to print the duplicate elements of an array
  1. public class DuplicateElement {  
  2.     public static void main(String[] args) {      
  3.           
  4.         //Initialize array   
  5.         int [] arr = new int [] {123427883};   
  6.           
  7.         System.out.println("Duplicate elements in given array: ");  
  8.         //Searches for duplicate element  
  9.         for(int i = 0; i < arr.length; i++) {  
  10.             for(int j = i + 1; j < arr.length; j++) {  
  11.                 if(arr[i] == arr[j])  
  12.                     System.out.println(arr[j]);  
  13.             }  
  14.         }  
  15.     }  
  16. }  
Output:
Duplicate elements in given array: 
2
3
8

Explanation

In this program, we need to print the duplicate elements present in the array. This can be done through two loops. The first loop will select an element and the second loop will iteration through the array by comparing the selected element with other elements. If a match is found, print the duplicate element.
Program to print the duplicate elements of an array
In the above array, the first duplicate will be found at the index 4 which is the duplicate of the element (2) present at index 1. So, duplicate elements in the above array are 2, 3 and 8.

Algorithm

  1. Declare and initialize an array.
  2. Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.
  3. If a match is found which means the duplicate element is found then, display the element.

Find Duplicate Elements from List?

The method add of set returns a boolean whether a value already exists (true if it does not exist, false if it already exists
package com.crunchify.tutorials;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
public class CrunchifyFindDuplicateInList {
    /**
     * @author Crunchify.com
     */
public static void main(String[] args) {
List<String> list = new LinkedList<String>();
for (int i = 0; i < 10; i++) {
list.add(String.valueOf(i));
}
for (int i = 0; i < 5; i++) {
list.add(String.valueOf(i));
}
System.out.println("My List : " + list);
System.out.println("\nHere are the duplicate elements from list : " + findDuplicates(list));
}
public static Set<String> findDuplicates(List<String> listContainingDuplicates) {
final Set<String> setToReturn = new HashSet<String>();
final Set<String> set1 = new HashSet<String>();
for (String yourInt : listContainingDuplicates) {
if (!set1.add(yourInt)) {
setToReturn.add(yourInt);
}
}
return setToReturn;
}
}

Output:

How to remove duplicates from ArrayList in Java?


To remove dupliates from ArrayList, we can convert it into Set. Since Set doesn't contain duplicate elements, it will have only unique elements.

  1. public class RemoveDuplicateArrayList {   
  2.     public static void main(String[] args) {  
  3.         List<String> l = new ArrayList<String>();  
  4.         l.add("Mango");  
  5.         l.add("Banana");  
  6.         l.add("Mango");  
  7.         l.add("Apple");  
  8.         System.out.println(l.toString());  
  9.         Set<String> s = new LinkedHashSet<String>(l);  
  10.         System.out.println(s);  
  11.     }  
  12. }  

Output:
Before converting to set
[Mango, Banana, Mango, Apple]
After converting to set
[Mango, Banana, Apple]



Removing duplicates from a String in Java

Convert the string to an array of char, and store it in a LinkedHashSet. That will preserve your ordering, and remove duplicates. Something like:
String string = "aabbccdefatafaz";

char[] chars = string.toCharArray();
Set<Character> charSet = new LinkedHashSet<Character>();
for (char c : chars) {
    charSet.add(c);
}

StringBuilder sb = new StringBuilder();
for (Character character : charSet) {
    sb.append(character);
}
System.out.println(sb.toString());
Remove duplicates in array using LinkedHashSet
 there is no pre-condition to not to use collections API then LinkedHashSet is the best approach for removing duplicate elements in an array. LinkedHashSet does two things internally :
  • Remove duplicate elements
  • Maintain the order of elements added to it
Java program to remove duplicates in array using LinkedHashSet. In given example, numbers is an integer array which has duplicate numbers 1, 3 and 5. We add all elements to LinkedHashSet, and then get back the content in array. The result array does not have duplicate integers.
ArrayExample.java
import java.util.Arrays;
import java.util.LinkedHashSet;
public class ArrayExample
{
    public static void main(String[] args) throws CloneNotSupportedException
    {
        //Array with duplicate elements
        Integer[] numbers = new Integer[] {1,2,3,4,5,1,3,5};
         
        //This array has duplicate elements
        System.out.println( Arrays.toString(numbers) );
         
        //Create set from array elements
        LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>( Arrays.asList(numbers) );
         
        //Get back the array without duplicates
        Integer[] numbersWithoutDuplicates = linkedHashSet.toArray(new Integer[] {});
         
        //Verify the array content
        System.out.println( Arrays.toString(numbersWithoutDuplicates) );
    }
}
Program Output.
Console
[12345135]
[12345]

Performance Test of String and StringBuffer

  1. public class ConcatTest{  
  2.     public static String concatWithString()    {  
  3.         String t = "Java";  
  4.         for (int i=0; i<10000; i++){  
  5.             t = t + "Tpoint";  
  6.         }  
  7.         return t;  
  8.     }  
  9.     public static String concatWithStringBuffer(){  
  10.         StringBuffer sb = new StringBuffer("Java");  
  11.         for (int i=0; i<10000; i++){  
  12.             sb.append("Tpoint");  
  13.         }  
  14.         return sb.toString();  
  15.     }  
  16.     public static void main(String[] args){  
  17.         long startTime = System.currentTimeMillis();  
  18.         concatWithString();  
  19.         System.out.println("Time taken by Concating with String: "+(System.currentTimeMillis()-startTime)+"ms");  
  20.         startTime = System.currentTimeMillis();  
  21.         concatWithStringBuffer();  
  22.         System.out.println("Time taken by Concating with  StringBuffer: "+(System.currentTimeMillis()-startTime)+"ms");  
  23.     }  
  24. }  

Time taken by Concating with String: 578ms
Time taken by Concating with  StringBuffer: 0ms

String and StringBuffer HashCode Test

As you can see in the program given below, String returns new hashcode value when you concat string but StringBuffer returns same
  1. public class InstanceTest{  
  2.     public static void main(String args[]){  
  3.         System.out.println("Hashcode test of String:");  
  4.         String str="java";  
  5.         System.out.println(str.hashCode());  
  6.         str=str+"tpoint";  
  7.         System.out.println(str.hashCode());  
  8.    
  9.         System.out.println("Hashcode test of StringBuffer:");  
  10.         StringBuffer sb=new StringBuffer("java");  
  11.         System.out.println(sb.hashCode());  
  12.         sb.append("tpoint");  
  13.         System.out.println(sb.hashCode());  
  14.     }  
  15. }  
Hashcode test of String:
3254818
229541438
Hashcode test of StringBuffer:
118352462
118352462

Performance Test of StringBuffer and StringBuilder

Let's see the code to check the performance of StringBuffer and StringBuilder classes
  1. //Java Program to demonstrate the performance of StringBuffer and StringBuilder classes.  
  2. public class ConcatTest{  
  3.     public static void main(String[] args){  
  4.         long startTime = System.currentTimeMillis();  
  5.         StringBuffer sb = new StringBuffer("Java");  
  6.         for (int i=0; i<10000; i++){  
  7.             sb.append("Tpoint");  
  8.         }  
  9.         System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - startTime) + "ms");  
  10.         startTime = System.currentTimeMillis();  
  11.         StringBuilder sb2 = new StringBuilder("Java");  
  12.         for (int i=0; i<10000; i++){  
  13.             sb2.append("Tpoint");  
  14.         }  
  15.         System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() - startTime) + "ms");  
  16.     }  
  17. }  
Time taken by StringBuffer: 16ms
Time taken by StringBuilder: 0ms



No comments:

Post a Comment