Add unique element to ArrayList with "dynamic" suffix

user2557930 :

I have seen similar question in Stack , but it was for files in C. The situation : I have an ArrayList of Strings , which element is an e-mail.For example:

[email protected]
[email protected]
[email protected]

etc.

i want to write a function/method which will add a new e-mail to that List with one very important catch !:

if for example i want to add "[email protected]" , the method should go through the ArrayList and if "[email protected]" already exist, then it checkes if "[email protected]" exists etc, until it finds free number suffix, and then add it.In our example it should add "[email protected]".

The problem is that i want some short and elegant sollution, what i wrote is ugly 150 lines of code with 3 methods etc, which just doesnt look ok. Anyone with a nice algorithm or perhaps advanced Collection feaute to accomplish that ?

Thanks

Ayrton :

You could check your list before adding, like this:

public void addWithSuffix(String email) {
    if(list.contains(email)) {
        int number = 0;
        String[] tmp = email.split("@");

        for(; list.contains(tmp[0] + number + "@" + tmp[1]); number++){}

        list.add((tmp[0] + number + "@" + tmp[1]));
    }
    else {
        list.add(email);
    }
}

But, of course, validating your inputs to ensure that the email is valid before trying to add it. And I'd also recommend swapping a List for a Set

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=114434&siteId=1