Home > Software engineering >  How to cast a String as an Array then dedupe Array in Java?
How to cast a String as an Array then dedupe Array in Java?

Time:04-28

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:

  1. You first need to split the string and get an array of string with the split elements.

  2. Then, pass the returned array to a Set in order to keep only the unique elements. Since a Set does not directly accept an array you first need to use the asList static method of the Arrays class.

  3. Finally, either print the Set or get an array from the Set 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));
  • Related