Java 8 streams finds the element and adds it to the beginning of the new list
I wonder if I can use the Java streams line to solve this problem: I need to find a string in the string list and create another list, where the search string (if found) will be the first string in the new list and then the remaining string values
For eg:
List<String> oldList = Arrays.asList("Avacado","Apple","Orange","Chocolate");
So now if you use the filter "chocolate" to search, it should return a new list containing "chocolate", "Avacado" elements, "apple", "orange"
List<String> newList = oldList.stream().filter(i -> i.equals("Chocolate")).collect(Collectors.toList()) ???
Solution
You are looking for a solution using stream This is a:
List<String> sorted = oldList.stream() .sorted(Comparator.comparing("Chocolate"::equals).reversed()) .collect(Collectors.toList()); System.out.println(sorted);
It gives:
[Chocolate,Avacado,Apple,Orange]
Therefore, only "chocolate" is moved in the first index
But actually you don't need a stream The list itself is sufficient:
oldList.sort(Comparator.comparing("Chocolate"::equals).reversed()); System.out.println(oldList);
The result is
[Chocolate,Orange]
... same
Editor: I updated my answer because @ Holger pointed out that it violated comparator Compare (O1, O2) contract I am using the solution proposed by Holger in his comments So he should be voted because I struggled twice to get the right solution
This method maps each string to a Boolean value indicating whether the string is equal to chocolate In the case of equality, if another string is not equal to "chocolate", then Boolean Compare (x, y) will return 1 for X and - 1 for y If x and y are equal to "chocolate", the result is 0 Because we want to move chocolate to the first index, its index must be reduced Therefore, a respectful comparator (1 = > - 1 and - 1 = > 1) is required