JAVA中对List
可以使用Java 8的Stream API和Comparator来对List
- 使用Stream API将List转换为Stream。
- 使用sorted方法对Stream中的元素进行排序,传入Comparator.comparing方法,并使用Lambda表达式指定要排序的Map中的key值。
- 使用collect方法将Stream转换为List。
示例代码如下:
List<Map<String, Object>> list = new ArrayList<>();
// 假设list中有多个Map元素,每个Map都包含“name”和“age”两个key值
List<Map<String, Object>> sortedList = list.stream()
.sorted(Comparator.comparing(m -> (String) m.get("name")))
.collect(Collectors.toList());
// 根据Map中的“name”值对List进行排序
注意:在使用Lambda表达式时,需要将Map中的value强制转换为对应的类型。
JAVA中对List
可以使用Java 8的Stream API和Comparator来对List
- 创建一个包含指定顺序的key值列表。
- 使用Stream API将List转换为Stream。
- 使用sorted方法对Stream中的元素进行排序,传入一个Comparator对象,并使用Lambda表达式指定排序的规则。在Lambda表达式中,首先使用indexOf方法获取当前Map的key值在指定顺序列表中的下标,然后使用compareTo方法对下标进行比较。
- 使用collect方法将Stream转换为List。
示例代码如下:
List<Map<String, Object>> list = new ArrayList<>();
// 假设list中有多个Map元素,每个Map都包含“name”和“age”两个key值
List<String> order = Arrays.asList("Tom", "Jerry", "Mike", "John");
// 假设按照指定顺序排序的key值为“name”,顺序为“Tom”、“Jerry”、“Mike”、“John”
List<Map<String, Object>> sortedList = list.stream()
.sorted(Comparator.comparing(m -> order.indexOf(m.get("name"))))
.collect(Collectors.toList());
// 根据Map中的“name”值按照指定顺序对List进行排序
注意:在使用Lambda表达式时,需要将Map中的value强制转换为对应的类型。在indexOf方法中,如果当前Map的key值不在指定顺序列表中,将会返回-1。