Reputation: 2649
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.
Upvotes: 10
Views: 5890
Reputation: 328608
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;
}
Upvotes: 10