Java 8 Streams查找元素并将其添加到新List的开头 [英] Java 8 Streams find element and add it to the start of the new List

查看:1551
本文介绍了Java 8 Streams查找元素并将其添加到新List的开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以使用Java Streams来解决这个问题:我需要在字符串列表中找到一个字符串并创建另一个列表,其中搜索字符串(如果找到)将是第一个字符串新的List,然后是其余的String值

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

对于Eg:

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

所以现在如果使用过滤器巧克力搜索它应该返回一个新列表,其中包含元素按巧克力,Avacado,
Apple,Orange。

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()) ???


推荐答案

您正在寻求使用<$ c的解决方案$ C>流。这是一个:

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

它给出:

[Chocolate, Avacado, Apple, Orange]

所以只有巧克力在第一个索引处被移动。

So only "Chocolate" was moved at first index.

但实际上你不需要 Stream 。列表本身就足够了:

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

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

结果是

[Chocolate, Avacado, Apple, Orange]

...相同。

编辑:

我更新了我的答案,因为@Holger指出它违反了 Comparator.compare的合同(O1,O2)。我正在使用Holger在他的评论中提出的解决方案。所以他应该被投票,因为我挣扎了两次以获得正确的解决方案。


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.

这种方法将每个字符串映射到 boolean 表示字符串是否等于Chocolate的值。如果相等 Boolean.compare(x,y)将返回 1 x -1 对于 y 如果另一个字符串不等于 巧克力。如果 x y 等于巧克力结果是 0

因为我们想将巧克力移动到第一个索引它是指数必须减少。因此,一个尊敬的比较器( 1 => -1 -1 => 1 )是必需的。

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.

这篇关于Java 8 Streams查找元素并将其添加到新List的开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆