Let’s say I have a String array, and I want to filter the array, reverse the order of the stream, and then combine the stream into one string.
Is it bad practice to include this to reverse the output order of the stream?:
**.sorted(Comparator.comparing(n -> counter[0]++)) **
(using an external int[] called counter I am able to reverse the array in the stream without having to quit the stream first).
So for example the code might look like:
String[] strs = {“Sally” “Sold” “Seashells” “By” “The” “Seashore”};
int[] counter = {0};
return Arrays.stream(strs).filter(n -> n.charAt(0)==“S”).sorted(Comparator.comparing(n -> counter[0]++)).collect(Collectors.joining(“ “));
So what the code would return is “Seashore Seashells Sold Sally”. I know that this method of reversing a streams order works as I’ve used it many many times without error on fun practice problem in places like leetcode and codewars.
How bad of a practice is this?
I expect it to be bad practice but it makes my life so easy sometimes. I feel like I have to type and think a lot less.
Pizmos is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.