Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Streams find element and add it to the start of the new List

I am wondering if this is possible to solve this problem with one line using Java Streams : i need to find a String in a list of strings and create another list where the search string (if found) will be the first string on the new List and then the rest of the String values

For Eg:

List<String> oldList = Arrays.asList("Avacado", "Apple", "Orange", "Chocolate");

So now if if search using say a filter "Chocolate" its should return a new list which will contain the elements in order "Chocolate", "Avacado", "Apple", "Orange".

List<String> newList =  oldList.stream().filter(i -> i.equals("Chocolate")).collect(Collectors.toList()) ???
like image 728
Joe Avatar asked Mar 06 '23 18:03

Joe


1 Answers

You're asking for a solution using Stream. This is one:

    List<String> sorted = oldList.stream()
            .sorted(Comparator.comparing("Chocolate"::equals).reversed())
            .collect(Collectors.toList());
    System.out.println(sorted);

And it gives:

[Chocolate, Avacado, Apple, Orange]

So only "Chocolate" was moved at first index.

But actually yon don't need a Stream. The list itself is enough:

oldList.sort(Comparator.comparing("Chocolate"::equals).reversed());
System.out.println(oldList);

The result is

[Chocolate, Avacado, Apple, Orange]

... the same.

EDIT:
I've updated my answer as @Holger pointed out that it violated the contract of Comparator.compare(o1,o2). I'm using the solution Holger suggested in his comment. So he should be upvoted as I struggled two times to get a correct solution.

This approach maps each string to a boolean value which states whether the string is equal to "Chocolate". In case of equality Boolean.compare(x,y) will return 1 for x and -1 for y if the other string is not equal to "Chocolate". If x and y are equal to "Chocolate" the result is 0.
As we want to move "Chocolate" to the first index it's index has to decrease. Thus a reveresed comparator (1 => -1 and -1 => 1) is needed.

like image 123
LuCio Avatar answered Apr 30 '23 12:04

LuCio