[英]Java list intersection in lambda and collect pair
I have two lists. 我有两个清单。 The insertion order into the "idOrderList" is also the sort order needed for the "idAndIndexList".
“ idOrderList”中的插入顺序也是“ idAndIndexList”所需的排序顺序。 I'm intersecting the list as below in the code.
我在代码中按如下所示与列表相交。
{
List<String> idOrderList; //insertion order in this list is sort order
List<Pair<String,Integer>> idAndIndexList;
//List intersection is done as below
List resultList =
idOrderList.stream().filter(
new HashSet<>(idAndIndexList.stream()
.flatMap(o -> Stream.of(o.getLeft(),o.getRight()))
.collect(Collectors.toList()))::contains)
.collect(Collectors.toList());
}
I'm stuck at how to collect the "Pair.getRight()" into the "resultList" or alternately I want to collect the "idAndIndexList" Pair as result but maintain the insertion order of "idOrderList". 我被困在如何将“ Pair.getRight()”收集到“ resultList”中,或者作为结果,我想收集“ idAndIndexList”对,但是要保持“ idOrderList”的插入顺序。 Any input or suggestions.
任何意见或建议。 Many Thanks in advance
提前谢谢了
The easiest approach is to convert idAndIndexList
into its corresponding right
value set and use Set.contains
. 最简单的方法是将
idAndIndexList
转换为其对应的right
值集并使用Set.contains
。 This also avoids running the idAndIndexList.stream()
pipeline multiple times unnecessarily: 这也避免了不必要地多次运行
idAndIndexList.stream()
管道:
Set<String> idSet = idAndIndexList.stream()
.map(Pair::getLeft)
.collect(Collectors.toSet());
List<String> resultList = idOrderList.stream()
.filter(idSet::contains)
.collect(Collectors.toList());
...alternately I want to collect the "idAndIndexList" Pair as result but maintain the insertion order of "idOrderList"
...或者我想收集“ idAndIndexList”对作为结果,但保持“ idOrderList”的插入顺序
Regarding this approach, you can use sorted
and sort items based on their index in idOrderList
: 关于这种方法,您可以根据
idOrderList
的索引使用sorted
和排序项目:
List<String> resultList2 = idAndIndexList.stream()
.map(Pair::getLeft)
.sorted(Comparator.comparingInt(idOrderList::indexOf)) //be careful here
.collect(Collectors.toList());
But it's important to note that if idAndIndexList
contains duplicates, the result may be something other than what you'd expect. 但是需要特别注意的是,如果
idAndIndexList
包含重复项,则结果可能与您期望的不同。 The first approach is more reliable in this case. 在这种情况下,第一种方法更可靠。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.