将Map <string,string>拆分为相等大小的List <map <string,string >>

时间:2019-04-24 18:54:17

标签: hashmap

我有一个Map Map,其中有5个条目,并想将其转换为List>,其中列表中的每个Map都有2个条目,最后一个条目具有剩余数据,例如1(5- 2 * 2 = 1)。

我知道我可以通过使用以下代码来首次获得它-

  Map<String, String> a = new HashMap<>();
         a.put("1","One");
         a.put("4","Two");
         a.put("5","Five");
         a.put("2","Two");
         a.put("3","Three");

a.entrySet().stream().sorted(Comparator.comparing(o->o.getKey())).limit(2).collect(Collectors.toList()));

有没有办法以简单的方式获得它?

1 个答案:

答案 0 :(得分:0)

我得到了下面的一段代码,按照上面提到的要求,它工作得很好-

public static <K, V> Collector<Map.Entry<K, V>, ?, List<Map<K, V>>> splitMap(int limit) {
    return Collector.of(ArrayList::new,
            (l, e) -> {
              if (l.isEmpty() || l.get(l.size() - 1).size() == limit) {
                l.add(new HashMap<>());
              }
              l.get(l.size() - 1).put(e.getKey(), e.getValue());
            },
            (l1, l2) -> {
              if (l1.isEmpty()) {
                return l2;
              }
              if (l2.isEmpty()) {
                return l1;
              }
              if (l1.get(l1.size() - 1).size() < limit) {
                Map<K, V> map = l1.get(l1.size() - 1);
                ListIterator<Map<K, V>> mapsIte = l2.listIterator(l2.size());
                while (mapsIte.hasPrevious() && map.size() < limit) {
                  Iterator<Map.Entry<K, V>> ite = mapsIte.previous().entrySet().iterator();
                  while (ite.hasNext() && map.size() < limit) {
                    Map.Entry<K, V> entry = ite.next();
                    map.put(entry.getKey(), entry.getValue());
                    ite.remove();
                  }
                  if (!ite.hasNext()) {
                    mapsIte.remove();
                  }
                }
              }
              l1.addAll(l2);
              return l1;
            }
    );
  }


List<Map<String,String>> listofMaps = a.entrySet().stream().collect(splitMap(2));
System.out.println(listofMaps);

输出-> [{1 =一个,2 =两个},{3 =三个,4 =两个},{5 =五个}]

相关问题