Can anyone please let me know how to remove duplicate values from
String s=\"Bangalore-Chennai-NewYork-Bangalore-Chennai\";
and output sh
This does it in one line:
public String deDup(String s) {
return new LinkedHashSet(Arrays.asList(s.split("-"))).toString().replaceAll("(^\\[|\\]$)", "").replace(", ", "-");
}
public static void main(String[] args) {
System.out.println(deDup("Bangalore-Chennai-NewYork-Bangalore-Chennai"));
}
Output:
Bangalore-Chennai-NewYork
Notice that the order is preserved :)
Key points are:
split("-") gives us the different values as an arrayArrays.asList() turns the array into a ListLinkedHashSet preserves uniqueness and insertion order - it does all the work of giving us the unique values, which are passed via the constructortoString() of a List is [element1, element2, ...]replace commands remove the "punctuation" from the toString()This solution requires the values to not contain the character sequence ", " - a reasonable requirement for such terse code.
Of course it's 1 line:
public String deDup(String s) {
return Arrays.stream(s.split("-")).distinct().collect(Collectors.joining("-"));
}
If you don't care about preserving order (ie it's OK to delete the first occurrence of a duplicate):
public String deDup(String s) {
return s.replaceAll("(\\b\\w+\\b)-(?=.*\\b\\1\\b)", "");
}