The cleanest solution is the one suggested by @SQLHacks. But then you said ABC:123a4
must be different from abc:1234A4
. I guess the only solution now is to create a wrapper for the String
objects and override the equals()
and hashCode()
method to do what you want, as @PaulBoddington suggested in his comment.
This is what I came up with (edited and improved based on @nafas answer):
public class StringWrapper {
private String value;
private String beforeColon;
private String afterColon;
private int hash;
public StringWrapper(String value) {
this.value = value;
String[] splitted = value.split(":");
beforeColon = splitted[0];
afterColon = splitted[1];
hash = Objects.hash(beforeColon.toUpperCase(), afterColon);
}
public String getValue() {
return value;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof StringWrapper) {
StringWrapper other = (StringWrapper) obj;
return beforeColon.equalsIgnoreCase(other.beforeColon) && afterColon.equals(other.afterColon);
}
return false;
}
@Override
public int hashCode() {
return hash;
}
@Override
public String toString() {
return value;
}
}
And then:
// this method is just to help you building a List<StringWrapper> from your String (memberList variable)
public static List<StringWrapper> split(String string, String regex) {
List<StringWrapper> list = new ArrayList<>();
for (String element : string.split(regex)) {
list.add(new StringWrapper(element));
}
return list;
}
public static void main(String[] args) {
String memberList = "ABC:123,abc:123,ABC:123a4,ABC:123A4";
List<StringWrapper> memlist = new ArrayList<>(split(memberList, ","));
Set<StringWrapper> memberSet = new HashSet<>(memlist);
memlist = new ArrayList<StringWrapper>(memberSet);
for (StringWrapper element : memlist) {
System.out.println(element);
}
}
If you run this, you get as output the following:
ABC:123a4
ABC:123A4
ABC:123
abc:123
is out but ABC:123a4
and ABC:123A4
are both present.
You can make things even easier changing the static split
method to create the Set
for you. The reason I didn't do that was to make things look familiar to you.