【发布时间】:2017-07-17 11:16:01
【问题描述】:
我有一个 Item 对象的 LinkedHashMap。项目有 itemId 和 Color。我想对我的地图数据进行排序和分组,地图是根据插入顺序以及分组颜色进行排序的。
让我用例子来演示
Map<String, ItemVO> itemChildMap = new LinkedHashMap<String, ItemVO>();
ItemVO item1 = new ItemVO("98091", "Red");
ItemVO item2 = new ItemVO("32456", "Black");
ItemVO item3 = new ItemVO("12323", "Green");
ItemVO item4 = new ItemVO("78956", "Red");
ItemVO item5 = new ItemVO("11231", "Green");
ItemVO item6 = new ItemVO("10098", "Black");
ItemVO item7 = new ItemVO("23410", "Red");
itemChildMap.put("98091", item1);
itemChildMap.put("32456", item2);
itemChildMap.put("12323", item3);
itemChildMap.put("78956", item4);
itemChildMap.put("11231", item5);
itemChildMap.put("10098", item6);
itemChildMap.put("23410", item7);
经过排序和分组逻辑后,map应该如下:
{98091=ItemVO [itemId='98091', color='Red']
, 78956=ItemVO [itemId='78956', color='Red']
, 23410=ItemVO [itemId='23410', color='Red']
, 32456=ItemVO [itemId='32456', color='Black']
, 10098=ItemVO [itemId='10098', color='Black']
, 12323=ItemVO [itemId='12323', color='Green']
, 11231=ItemVO [itemId='11231', color='Green']
}
基本上,地图应该首先包含所有具有红色的项目对象(首先插入),然后是具有黑色的项目对象,最后是具有绿色的项目对象。
【问题讨论】:
-
我曾经需要同样的东西。这有帮助:https://stackoverflow.com/a/2581754/7399631
-
分组后是否也要保持组中的插入顺序?
-
嘿@mumpitz/ @OH GOD SPIDERS,在那个解决方案中只是关于排序,我已经检查过了。
-
嗨@AshishLohia,如果我们也能在组中保持插入顺序就好了(非强制性)