Consider in jQuery the following code to convert a string
into an array
and then dedupe said array
by first converting it to a string
and then cast it as a array
again in order to leverage a powerful $.unique()
jQuery function.
var daysProxyArray = "Monday,Monday,Friday,Friday".split(',');
daysProxyArray = $.unique(daysProxyArray.toString().split(','));
console.log(daysProxyArray.toString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Does anyone know how to do the equivalent in Java in one line where the end result is a string that I can count how many times a comma appears? Such that, if 2 commas appear, I will know that 3 unique days were in the original string.
CodePudding user response:
If you want to count the amount of commas the following code should do the trick (in Java 8 ):
String text = "Monday,Monday,Friday,Friday";
long numCommas = text.chars().filter(c -> c == ',').count();
CodePudding user response:
Arrays.stream("Monday,Monday,Friday,Friday".split(","))
.distinct()
.collect(Collectors.joining(","));
CodePudding user response:
To achieve in Java what you're doing in JQuery:
You first need to split the string and get an array of string with the split elements.
Then, pass the returned array to a
Set
in order to keep only the unique elements. Since aSet
does not directly accept an array you first need to use theasList
static method of theArrays
class.Finally, either print the
Set
or get an array from theSet
and print that.
//Splitting the string
String[] daysProxyArray = "Monday,Monday,Friday,Friday".split(",");
//Using a collection set to only keep the unique elements
Set<String> set = new HashSet(Arrays.asList(daysProxyArray));
//You could either print the set...
System.out.println(set);
//...Or returning the set's elements into an array and use that if you actually need an array
String[] res = new String[0];
res = set.toArray(res);
System.out.println(Arrays.toString(res));