MapUtil

Introduction

MapUtil is a set of utility methods for Map, including shortcut value conversion methods for getXXX.

Methods

  • isEmpty and isNotEmpty methods to check if a Map is empty or not. An empty Map is defined as null or having no values.
  • newHashMap method to quickly create various types of HashMap instances.
  • createMap method to create a custom type of Map.
  • of method to add one or more key-value pairs to a newly created Map. Here’s an example:
Map<Object, Object> colorMap = MapUtil.of(new String[][] {
     {"RED", "#FF0000"},
     {"GREEN", "#00FF00"},
     {"BLUE", "#0000FF"}
});
  • toListMap method to convert rows to columns, merging identical keys and combining their values into lists. For example, if the input data is:
[
  {a: 1, b: 1, c: 1},
  {a: 2, b: 2},
  {a: 3, b: 3},
  {a: 4}
]

The result will be:

{
   a: [1,2,3,4],
   b: [1,2,3,],
   c: [1]
}
  • toMapList method to convert columns to rows. It takes a Map with list values and creates new Maps by combining the list elements with their corresponding keys. For example, if the input data is:
{
   a: [1,2,3,4],
   b: [1,2,3,],
   c: [1]
}

The result will be:

[
  {a: 1, b: 1, c: 1},
  {a: 2, b: 2},
  {a: 3, b: 3},
  {a: 4}
]
  • join, joinIgnoreNull, and sortJoin methods to convert a Map to a string with a given delimiter. These methods are typically used for signing. Here’s an example:
Map<String, String> build = MapUtil.builder(new HashMap<String, String>())
 .put("key1", "value1")
 .put("key3", "value3")
 .put("key2", "value2").build();
 
// key1value1key2value2key3value3
String join1 = MapUtil.sortJoin(build, StrUtil.EMPTY, StrUtil.EMPTY, false);
// key1value1key2value2key3value3123
String join2 = MapUtil.sortJoin(build, StrUtil.EMPTY, StrUtil.EMPTY, false, "123");
  • filter method to filter elements based on an Editor implementation. The Editor implementation can perform the following functions: 1) filter out the desired object by returning null for elements that should be discarded, and 2) modify the element object and return the modified object in the collection. Here’s an example:
Map<String, String> map = MapUtil.newHashMap();
map.put("a", "1");
map.put("b", "2");
map.put("c", "3");
map.put("d", "4");
 
Map<String, String> map2 = MapUtil.filter(map, (Filter<Entry<String, String>>) t -> Convert.toIn(t.getValue()) % 2 == 0);