我有一个Map,它的键是string,值是string[]。
Map<String,String[]> map = new HashMap<>();
map.put("String1", new String[]{ "abc", "dfe", "new"});
map.put("String8", new String[]{"xyz","hji","new"});
map.put("String2", new String[]{"abc","dfe","old"});
map.put("String3", new String[]{"abc","dfe","past"});
map.put("String5", new String[]{"xyz","hji","ancient"});
map.put("String6",new String[]{"xyz","hji","past"});
map.put("String4", new String[]{"abc","dfe","ancient"});
map.put("String7", new String[]{"xyz","hji","old"});
我想使用值打印Map分组。
值是字符串的数组。
字符串数组的前两个元素将用于分组。
代码必须找到类似的值并按值分组,而不通过任何过滤器。
最终输出如下所示:
String1:[{ "abc", "dfe", "new"}]
String2:[{"abc","dfe","old"}]
String3:[{"abc","dfe","past"}]
String4:[{"abc","dfe","ancient"}]
String5:[{"xyz","hji","ancient"}]
String6:[{"xyz","hji","past"}]
String7:[{"xyz","hji","old"}]
String8:[{"xyz","hji","new"}]
如何在Java8中实现这一点?
4条答案
按热度按时间ifmq2ha21#
根据您的输出,您似乎只想根据键进行排序。所以你可以这样做。创建一个
SortedMap
只需将当前Map添加到构造函数中即可。印刷品
soat7uwm2#
您可以通过如下方式进行双重分组:
ej83mcc03#
如果您只想根据键进行排序,则可以使用java 8:
输出将是:
mzmfm0qo4#
正如您所提到的,您希望根据数组的前2个元素(值)对Map进行排序,然后您可以尝试使用comparator:
根据值对数组的前2个元素进行分组,然后进行排序:
输出将基于值数组的前2个元素: