简体   繁体   中英

Convert a list of strings to a list of maps using Java streams

I have a list of strings in the following pattern

String test ="name=john,age=28;name=paul,age=30;name=adam,age=50";
List<String> listOfStrings = Arrays.asList(test.split(";"));

I want to convert the above list of strings to a list of map of key value pairs (like shown below).

[{name=john, age=28}, {name=paul, age=30}, {name=adam, age=50}]

Each entry in the above list a map with keys as name and age and values as their corresponding values.

This is what I have done to achieve the result.

listOfStrings.stream()
  .map(record -> Arrays.asList(record.split(",")).stream().map(field -> field.split("="))
  .collect(Collectors.toMap(keyValue -> keyValue[0].trim(), keyValue -> keyValue[1].trim())))
  .collect(Collectors.toList());

I would like to know if that is efficient or if there is a better way to do it using Java streams.

Here is another alternative using pattern matching, not as fast as a for loop but much faster than the original stream solution in my measurements.

public static void main(String[] args) {
    String test ="name=john,age=28;name=paul,age=30;name=adam,age=50";
    String patternString = "(name)=(\\w*),(age)=(\\d*)[;]?";
    Pattern pattern = Pattern.compile(patternString);
    Matcher matcher = pattern.matcher(test);
    List<Map<String, String>> list = new ArrayList<>();

    while (matcher.find()) {
        Map<String, String> map = new HashMap<>();
        map.put(matcher.group(1), matcher.group(2));
        map.put(matcher.group(3), matcher.group(4));
        list.add(map);
    }
}

A slight performance improvement could be had by not matching against the keys (name & age) and instead hardcoding them when creating the map elements.

If you are out for performace, ditch the Stream API. Especially streams with substreams are really bad for writing highly performant applications.

Here is a comparison of your Stream API version vs. a plain old for-loop:

public static void main(String[] args) {
  final String test = "name=john,age=28;name=paul,age=30;name=adam,age=50";

  final List<Map<String, String>> result1 = loop(test);
  final List<Map<String, String>> result2 = stream(test);

  System.out.println(result1);
  System.out.println(result2);
}


private static List<Map<String, String>> loop(String str) {
  long start = System.nanoTime();

  List<Map<String, String>> result = new ArrayList<>();
  String[] persons = str.split(";");

  for (String person : persons) {
    String[] attributes = person.split(",");
    Map<String, String> attributeMapping = new HashMap<>();

    for (String attribute : attributes) {
      String[] attributeParts = attribute.split("=");

      attributeMapping.put(attributeParts[0], attributeParts[1]);
    }

    result.add(attributeMapping);
  }

  long end = System.nanoTime();
  System.out.printf("%d nano seconds\n", (end - start));

  return result;
}

private static List<Map<String, String>> stream(final String str) {
  long start = System.nanoTime();

  List<String> listOfStrings = Arrays.asList(str.split(";"));
  List<Map<String, String>> result = listOfStrings.stream()
    .map(record -> Arrays.asList(record.split(",")).stream().map(field -> field.split("="))
    .collect(Collectors.toMap(keyValue -> keyValue[0].trim(), keyValue -> keyValue[1].trim())))
    .collect(Collectors.toList());

  long end = System.nanoTime();

  System.out.printf("%d nano seconds\n", (end - start));

  return result;
}

Outpout:

183887 nano seconds

53722108 nano seconds

[{name=john, age=28}, {name=paul, age=30}, {name=adam, age=50}]

[{name=john, age=28}, {name=paul, age=30}, {name=adam, age=50}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM