Utsav Sharma
Utsav Sharma

Reputation: 49

Remove case sensitive duplicate elements from list in java

So I have let's say a list of Strings like {"a","A","b","B","C","D","d","E"}

My requirement is that I want to remove duplicate elements from this string. I will specify in beginning whether elements to be considered for removing will be in lowercase or uppercase.

I know traditional approaches like using a for loop and then processing each element based on requirement. But I want to know much better approach to achieve this using java.

This is my approach :

String[] str = { "a", "A", "b", "B", "C", "D", "d", "E" }; HashSet s = new HashSet();

    for (String alphabet : str) {

        if (alphabet.equals(alphabet.toUpperCase())) {

            s.add(alphabet);
        }
    }       

    System.out.println(s);

Upvotes: 1

Views: 2346

Answers (4)

Ajay Kr Choudhary
Ajay Kr Choudhary

Reputation: 1372

Check this code below.

The idea is to create a count map of string. If an element has occurred once, add it directly to the de-duplicated list. If it has occurred more than once, you need to check which version of the element you want to keep(either lowercase or uppercase).

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;

public class RemoveDuplicateCaseInsensitive {
    public static void main(String[] args) {
        List<String> inputList = Arrays.asList("a", "A", "b", "B", "C", "D", "d", "E");
        Scanner scanner = new Scanner(System.in);
        String caseToRemove = scanner.nextLine();
        System.out.println("caseToRemove is = " + caseToRemove); // to be inputted by user
        Map<String, Long> countMapOfString =
                inputList.stream().collect(Collectors.groupingBy(String::toLowerCase, Collectors.counting()));

        System.out.println("countMapOfString is = " + countMapOfString);

        List<String> deDuplicatedStringList = new ArrayList<>();
        inputList.stream().forEach(element -> {
            // element which have occurred only once should be added straight away
            if (countMapOfString.get(element.toLowerCase()) == 1) {
                deDuplicatedStringList.add(element);
            } else {
                if (caseToRemove.equalsIgnoreCase("UpperCase")) { // want to remove uppercase
                    if (!deDuplicatedStringList.contains(element.toLowerCase())) {
                        deDuplicatedStringList.add(element.toLowerCase());
                    }
                } else if (caseToRemove.equalsIgnoreCase("LowerCase")) { // want to remove lowercase
                    if (!deDuplicatedStringList.contains(element.toUpperCase())) {
                        deDuplicatedStringList.add(element.toUpperCase());
                    }
                }
            }
        });
        System.out.println("deDuplicatedStringList is = " + deDuplicatedStringList);
    }
}

When you run with LowerCase as input the output of the program is

caseToRemove is = LowerCase
countMapOfString is = {a=2, b=2, c=1, d=2, e=1}
deDuplicatedStringList is = [A, B, C, D, E]

When you run with UpperCase as input the output of the program is

caseToRemove is = UpperCase
countMapOfString is = {a=2, b=2, c=1, d=2, e=1}
deDuplicatedStringList is = [a, b, C, d, E]

Hope this helps.

Upvotes: 0

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79425

Do it as follows:

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        String[] str = { "a", "A", "b", "B", "C", "D", "d", "E" };
        int option = 1;// `0` for lowercase and `1` for UPPERCASE
        Set<String> set;
        if (option == 0) {
            set = Arrays.stream(str).map(String::toLowerCase).collect(Collectors.toSet());
        } else {
            set = Arrays.stream(str).map(String::toUpperCase).collect(Collectors.toSet());
        }

        // Display
        System.out.println(set);
    }
}

Output:

[A, B, C, D, E]

Upvotes: 2

Charlie Armstrong
Charlie Armstrong

Reputation: 2342

Consider using a Set. Sets don't allow you to add duplicate items, and they are case sensitive. An example is below:

HashSet<String> set = new HashSet<>();
set.add("A");
set.add("a");
set.add("b");
set.add("B");
set.add("C");
set.add("D");
set.add("d");
set.add("E");

set.add("E"); //duplicate element
set.add("e"); //not a duplicate element

System.out.println(set.toString());

Output:

[A, a, b, B, C, D, d, E, e]

Upvotes: 0

J. B
J. B

Reputation: 129

For future reference, please include any code you've already tried. Because you haven't, I will explain some of the ways it is possible.

A for loop is definitely the easiest (and, correct me if I'm wrong, fastest) way to do this. You could use a foreach loop (for(thingContained name : groupOfContainedThings)) and check if there is a difference between the original character and one that has had the .toLowerCase() method called on it. if they're different, then it was an uppercase letter.

You could also instead use .compareTo(String str) with the above for loop, and check if the value is 0 (no difference). You can read more about it here. This is more versatile, and I recommend it because it will work with longer Strings too!

Upvotes: 1

Related Questions