Skip to content
Advertisement

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.

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

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

Advertisement

Answer

You can compare the boolean values which are returned by Set.contains and reverse the order just by negating it, since 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:

Set<String> set2 = list.stream()
                       .sorted(Comparator.comparing(set::contains).reversed())
                       .collect(Collectors.toCollection(LinkedHashSet::new));
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement