简体   繁体   中英

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM