动态多字段排序
动态多字段排序
假设我们有一个 Person
类,希望能够按照 age
和 name
进行动态排序。我们使用上述代码生成一个组合比较器来完成多字段排序。
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. 使用 Stream
和 Comparator
进行动态排序
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
标签:java,Stream,get,util,Person,API,import,Java,attributes From: https://www.cnblogs.com/spicy-food/p/18263548