madan madan - 18 days ago 5
Java Question

printing the duplicates characters in a line with same characters

I am trying one problem that is :
Print the duplicate values line by line from an array i.e each line having same character

Example :

Array arr1={a,a,a,a,b,b,b,b,c,c,c,c,e,e,g,f,h};


output should be like :

aaaa
bbbb
cccc
ee
g
f
h

Answer

You need to ensure input is sorted first, i.e. with Arrays.sort(). Once it is you can loop over the input and print each character. Whenever the next character is different print a new line.

Another alternative would be to create some kind of storage of counts of each character, e.g. LinkedHashMap(), but that would be over engineering IMO.

char[] arr1 = { 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'e', 'e', 'g', 'f', 'h' };

Arrays.sort(arr1);
for (int i = 0; i < arr1.length; i++) {
    char each = arr1[i];
    System.out.print(each);
    if (i + 1 < arr1.length && arr1[i + 1] != each) {
        System.out.println();
    }
}

Output

aaaa
bbbb
cccc
ee
f
g
h