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
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.

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
- Declare and initialize an array.
- 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.
- 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:
My List : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4]
Here are the duplicate elements from list : [3, 2, 1, 0, 4]
My List : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4]
Here are the duplicate elements from list : [3, 2, 1, 0, 4]
|
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.
- public class RemoveDuplicateArrayList {
- public static void main(String[] args) {
- List<String> l = new ArrayList<String>();
- l.add("Mango");
- l.add("Banana");
- l.add("Mango");
- l.add("Apple");
- System.out.println(l.toString());
- Set<String> s = new LinkedHashSet<String>(l);
- System.out.println(s);
- }
- }
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.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.
[ 1 , 2 , 3 , 4 , 5 , 1 , 3 , 5 ] [ 1 , 2 , 3 , 4 , 5 ] |
Performance Test of String and StringBuffer
- public class ConcatTest{
- public static String concatWithString() {
- String t = "Java";
- for (int i=0; i<10000; i++){
- t = t + "Tpoint";
- }
- return t;
- }
- public static String concatWithStringBuffer(){
- StringBuffer sb = new StringBuffer("Java");
- for (int i=0; i<10000; i++){
- sb.append("Tpoint");
- }
- return sb.toString();
- }
- public static void main(String[] args){
- long startTime = System.currentTimeMillis();
- concatWithString();
- System.out.println("Time taken by Concating with String: "+(System.currentTimeMillis()-startTime)+"ms");
- startTime = System.currentTimeMillis();
- concatWithStringBuffer();
- System.out.println("Time taken by Concating with StringBuffer: "+(System.currentTimeMillis()-startTime)+"ms");
- }
- }
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
- public class InstanceTest{
- public static void main(String args[]){
- System.out.println("Hashcode test of String:");
- String str="java";
- System.out.println(str.hashCode());
- str=str+"tpoint";
- System.out.println(str.hashCode());
- System.out.println("Hashcode test of StringBuffer:");
- StringBuffer sb=new StringBuffer("java");
- System.out.println(sb.hashCode());
- sb.append("tpoint");
- System.out.println(sb.hashCode());
- }
- }
Hashcode test of String: 3254818 229541438 Hashcode test of StringBuffer: 118352462 118352462Performance Test of StringBuffer and StringBuilder
Let's see the code to check the performance of StringBuffer and StringBuilder classes
- //Java Program to demonstrate the performance of StringBuffer and StringBuilder classes.
- public class ConcatTest{
- public static void main(String[] args){
- long startTime = System.currentTimeMillis();
- StringBuffer sb = new StringBuffer("Java");
- for (int i=0; i<10000; i++){
- sb.append("Tpoint");
- }
- System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - startTime) + "ms");
- startTime = System.currentTimeMillis();
- StringBuilder sb2 = new StringBuilder("Java");
- for (int i=0; i<10000; i++){
- sb2.append("Tpoint");
- }
- System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() - startTime) + "ms");
- }
- }
Time taken by StringBuffer: 16ms Time taken by StringBuilder: 0ms
No comments:
Post a Comment