Java Stream 8 API

动态多字段排序

动态多字段排序

假设我们有一个 Person 类,希望能够按照 agename 进行动态排序。我们使用上述代码生成一个组合比较器来完成多字段排序。

1. 定义 Person

java
import java.util.HashMap; import java.util.Map; public class Person { private Map<String, Comparable<?>> attributes = new HashMap<>(); public Person(String name, int age, double salary) { attributes.put("name", name); attributes.put("age", age); attributes.put("salary", salary); } public Comparable<?> get(String attributeName) { return attributes.get(attributeName); } @Override public String toString() { return "Person{name=" + attributes.get("name") + ", age=" + attributes.get("age") + ", salary=" + attributes.get("salary") + '}'; } }

2. 使用 StreamComparator 进行动态排序

java
import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.stream.Stream; import java.util.stream.Collectors; public class DynamicSortingExample { public static void main(String[] args) { List<Person> people = Arrays.asList( new Person("Alice", 30, 70000), new Person("Bob", 25, 60000), new Person("Charlie", 35, 80000), new Person("David", 30, 75000) ); // 定义要排序的列 List<String> columns = Arrays.asList("age", "name"); // 生成组合比较器 Optional<Comparator<Person>> combinedComparator = columns.stream() .map(column -> Comparator.comparing((Person p) -> p.get(column), Comparator.naturalOrder())) .reduce(Comparator::thenComparing); // 使用组合比较器进行排序 if (combinedComparator.isPresent()) { List<Person> sortedPeople = people.stream() .sorted(combinedComparator.get()) .collect(Collectors.toList()); sortedPeople.forEach(System.out::println); } } }

 

 

BiConsumer

Function

Turple

Triple

 

posted @ 2024-06-23 16:13  我爱麻辣香锅  阅读(4)  评论(0编辑  收藏  举报