我的列表就像
List<Map<String, Object>> sortedList = new ArrayList<>();
我的列表所在的位置
[{column_changed = first_name,sequence_number = 190001,change_date = 2019-01-01,customer_number = 3100}, {column_changed =姓氏,sequence_number = 190001,change_date = 2019-01-01,customer_number = 3100}, {column_changed = mail_id,sequence_number = 19002,change_date = 2019-01-05,customer_number = 3101}, {column_changed =出生日期,sequence_number = 190002,change_date = 2019-01-05,customer_number = 3101}, {column_changed =国籍,sequence_number = 190002,change_date = 2019-01-05,customer_number = 3101}, {column_changed = contact_number,sequence_number = 19003,change_date = 2019-01-10,customer_number = 3102}]
我按如下所示初始化Map的实例,
Map<String, List<Map<String, Object>>> mySortedMap = new TreeMap<>();
当我通过sequence_number使用Collectors.groupingBy()时,
mySortedMap = sortedList.stream().collect(Collectors.groupingBy(change -> (String)change.get("sequence_number")));
输出如下,
{190001 = [{column_changed = first_name,sequence_number = 190001,change_date = 2019-01-01,customer_number = 3100}, {column_changed =姓氏,sequence_number = 190001,change_date = 2019-01-01,customer_number = 3100}], 19003 = [{column_changed = contact_number,sequence_number = 19003,change_date = 2019-01-10,customer_number = 3102}], 19002 = [{column_changed = mail_id,sequence_number = 19002,change_date = 2019-01-05,customer_number = 3101}, {column_changed =出生日期,sequence_number = 190002,change_date = 2019-01-05,customer_number = 3101}, {column_changed =国籍,sequence_number = 190002,change_date = 2019-01-05,customer_number = 3101}]}
但是我需要对键进行排序。尽管实例是TreeMap,但键未排序。我不知道为什么。谁能帮我这个忙。
答案 0 :(得分:3)
在这里,您正在更改mySortedMap引用的对象。 groupingBy()返回的地图可以是任何类型。从文档中,
无法保证返回的Map或List对象的类型,可变性,可序列化性或线程安全性。
如果您的列表已排序,请尝试使用
mySortedMap = sortedList.stream().collect(Collectors.groupingBy(
change -> (String) change.get("sequence_number"), TreeMap::new, Collectors.toList()));