简体   繁体   English

基于交叉点的 Java 排序列表

[英]Java Sort List Based Off Intersections

I'm trying to see how I can sort a list using streams where items that exist in a separate hashset are moved to the front of the list.我正在尝试查看如何使用流对列表进行排序,其中存在于单独哈希集中的项目被移动到列表的前面。

Example:例子:

Set<Object> set;
List<Object> list;

I'm assuming I can use a lambda in streams.sorted() for this but I'm not able to figure out what this would look like.我假设我可以在 streams.sorted() 中使用 lambda,但我无法弄清楚这会是什么样子。

sizes.stream()
                    .sorted((o1, o2) -> {
                        ...

                        ...
                    })
                    .collect(Collectors.toCollection(LinkedHashSet::new));

You can compare the boolean values which are returned by Set.contains and reverse the order just by negating it, since false < true .您可以比较Set.contains返回的布尔值并通过否定它来反转顺序,因为false < true Example using strings:使用字符串的示例:

Set<String> set = Set.of("foo","bar","baz");
List<String> list = List.of("doo","dee","daa","foo","baz","bar");

Set<String> set2 = list.stream()
                       .sorted((o1,o2) -> - Boolean.compare(set.contains(o1),set.contains(o2)))
                       .collect(Collectors.toCollection(LinkedHashSet::new));

But you can gain readablity if you use method refernce instead of lambda:但是如果你使用方法引用而不是 lambda,你可以获得可读性:

Set<String> set2 = list.stream()
                       .sorted(Comparator.comparing(set::contains).reversed())
                       .collect(Collectors.toCollection(LinkedHashSet::new));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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