Dom
Dom

Reputation: 159

Can you equalsIgnoreCase a Set?

So, say I have a program, and the users target in the Set is called 'Computer'. The user enters in 'computer', 'COMPUTER','ComPutEr', but it never finds it because it's not capitalized correctly.

How would you go about taking a Set words = ... ... ... and taking the information inside of Set and checking if it is equal to 'Computer', but ignoring capitalization. Oooor! Making it so everything else is lowercase, but the first character.

Example Code:

Set<String> words= this.getConfig().getConfigurationSection("Test").getKeys(false);
    if( allGroups.contains('Computer') ) {

Please ignore the this.getConfig().getConfigurationSection("Test").getKeys(false);. I am looking for an answer to fix a Minecraft plugin I'm making, but this seems like a more basic Java knowledge question.

Thank you for the help guys

Upvotes: 2

Views: 797

Answers (2)

Dom
Dom

Reputation: 159

I ended up solving the problem, thanks to Elliot bringing it to my attention.

Set<String> words= new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
words.addAll(this.getConfig().getConfigurationSection("Test").getKeys(false));

args[0] = args[0].toLowerCase();
args[0] = args[0].substring(0, 1).toUpperCase() + args[0].substring(1);

if( words.contains(args[0]) ) {

Although this is not a great way of going about it in my book, I have used this same method of solving this problem with an ATM program I wrote. I'm currently thinking of a way to make the String 'args[0]' just 1 line to fix it all, but this is what currently works for me.

Thanks!

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201467

You could possibly use a TreeSet because it sorts the input it can take a comparator. Using that you could implement the behaviour you want. Something like

Comparator<String> comparator = new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
        if (o1 == o2) {
            return 0;
        }
        if (o1 == null) {
            return -1;
        } else if (o2 == null) {
            return 1;
        }
        return o1.toLowerCase().compareTo(o2.toLowerCase());
    }
};
Set<String> set = new TreeSet<>(comparator);

Or (from the comments) String.CASE_INSENSITIVE_ORDER like

Set<String> set = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);

Upvotes: 2

Related Questions