Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move specific objects to the beginning of a list using java 8 Stream API?

Consider this list of String

List<String> list = Arrays.asList("c", "k", "f", "e", "k", "d");

What i want to do is to move all k Strings to the beginning of the list and keep the rest at the same order.

What i have tried so far (it is working but i think it is so ugly)

list = Stream.concat(list.stream().filter(s -> s.equals("k")),
        list.stream().filter(s -> !s.equals("k"))).collect(
        Collectors.toCollection(ArrayList::new));

list.stream().forEach(System.out::print);

Output:

kkcfed

I am asking if there is another Stream features which i don't know to help me solve the problem more efficiently.

like image 998
MChaker Avatar asked May 17 '15 11:05

MChaker


People also ask

How do you filter a list of objects using a stream?

Java stream provides a method filter() to filter stream elements on the basis of given predicate. Suppose you want to get only even elements of your list then you can do this easily with the help of filter method. This method takes predicate as an argument and returns a stream of consisting of resulted elements.

Does stream filter modify the original list?

stream(). filter(i -> i >= 3); does not change original list. All stream operations are non-interfering (none of them modify the data source), as long as the parameters that you give to them are non-interfering too.

How do I skip the first element in a stream?

Java Stream skip() Stream skip(n) method is used to skip the first 'n' elements from the given Stream. The skip() method returns a new Stream consisting of the remaining elements of the original Stream, after the specified n elements have been discarded in the encounter order.


1 Answers

You could use a custom comparator:

list.stream()
        .sorted((s1, s2) -> "k".equals(s1) ? -1 : "k".equals(s2) ? 1 : 0)
        .forEach(System.out::print);

For better readability you could also extract it in a separate method:

public static void main(String[] args) {
  List<String> list = Arrays.asList("c", "k", "f", "e", "k", "d");
  list.stream()
          .sorted(kFirst())
          .forEach(System.out::print);
}

private static Comparator<? super String> kFirst() {
  return (s1, s2) -> "k".equals(s1) ? -1 : "k".equals(s2) ? 1 : 0;
}
like image 195
assylias Avatar answered Oct 18 '22 10:10

assylias