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.
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With