DEV Community

Suresh Ayyanna
Suresh Ayyanna

Posted on

3 1 1 1 1

Remove Duplicate Characters from given string(Java)

Program to print to Remove Duplicate Characters from given string

package InterviewPrograms;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class RemoveDuplicateFromString {
    public static void main(String[] args) {

        String str = "abbaaca";
        char y[] = str.toCharArray();
        int size = y.length;

        Map<Character, Integer> map = new LinkedHashMap<>();

        int i = 0;
        while (i != size) {
            if (map.containsKey(y[i]) == false) {
                map.put(y[i], 1);
            } else {
                int oldval = map.get(y[i]);
                int newval = oldval + 1;
                map.put(y[i], newval);
            }
            ++i;
        }
        Set<Map.Entry<Character, Integer>> lhmap = map.entrySet();
        String result = "";
        for (Map.Entry<Character, Integer> data : lhmap) {
            result = result + data.getKey();
        }
        System.out.println(result);
    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
jingxue profile image
Jing Xue

If you are allowed to use streams, this would do:

Stream.of(str.toCharArray()).collect(Collectors.toSet()).stream().collect(Collectors.joining())
Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay