Vicky
Vicky

Reputation: 21

How to print characters in character array without duplicate?

I was asked to write a program to print values in a character array. This array contains duplicated values, but output should not contain duplicated characters.Do not use Set. This is what I have created. Let me know if there is any other and efficient way to do the same.

public class RemoveDuplication {
  public static void main (String[] args){
    char[] a= new char[]{'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c'};
    String s=Character.toString(a[0]);

    for (int i=1; i<a.length; i++) {
      if ((s.indexOf(a[i])) == -1) {
        s = s + Character.toString(a[i]);
      } else {
      }
    }
    // if you want character array as result 
    char[] result = s.toCharArray();
    System.out.println(result);
  }
}

Upvotes: 2

Views: 1089

Answers (5)

nidomiro
nidomiro

Reputation: 830

What you could do to speedup this is something like, check if the character C is in the outputted characters array A (not the print) using binary search. Print the character C if it's not in the list and then insert (sorted) the character C to A (to be able to use binary search).

Upvotes: 0

Kaushik NP
Kaushik NP

Reputation: 6789

Each time I hear unique elements, Sets comes to my mind. So here is the easiest implementation using sets:

char[] a= new char[]{'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c'};

Set<Character> set = new HashSet<Character>(); //declare Set of Character type
for(char c : a)
        set.add(c);           //Add chars in 'a' to the set 

System.out.println(set);

OUTPUT : [a, b, c]

Upvotes: 0

David Conrad
David Conrad

Reputation: 16429

Stream the characters, filter to only distinct code points, then collect the code points in a StringBuilder and finally print it out:

System.out.println(
    str.chars().distinct().boxed()
        .collect(Collector.of(StringBuilder::new,
                    StringBuilder::appendCodePoint,
                    StringBuilder::append)));

Upvotes: 0

l12 323
l12 323

Reputation: 19

If you use a Set object, it will do that for you.

Set<Character> s = new HashSet<>();
s.add('c');
s.add('c');
//c was only added once

then iterate like this:

for(Character c: s)
{
    System.out.println(c);
}

Upvotes: 1

GhostCat
GhostCat

Reputation: 140641

You are over-doing.

Just go for:

StringBuilder builder = new StringBuilder().append(a[0]);

and then append() to that builder object; and in the end; call builder.toString(). Instead of all the funny things you do with that s string variable.

Your code that is going from and back between String and Character and using + for string appending is as said; very much over-complicating things.

Upvotes: 1

Related Questions