Skip to content
Advertisement

How to cast a String as an Array then dedupe Array in Java? [closed]

The core focus of this question is to manipulate a string with comma delimiters and duplicate entries in Java so that it returns a deduped, comma delimited string (all in one line and using native classes).

A.) Cast a comma delimited string as an Array,

B.) Dedupe that Array and then convert it back to a string

C.) Check against that newly deduped string to see how many unique entries there were, such that 1 commas means that there were 2 original unique entries.

D.) All of the above must be condensed into one line if possible. (If not, at least A and B is one line and C is its own line.

The following is a reference/picture of what is outlined above using JavaScript and jQuery. It is only anecdotal.

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.

Advertisement

Answer

Arrays.stream("Monday,Monday,Friday,Friday".split(","))
                .distinct()
                .collect(Collectors.joining(","));
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement