Java8 converts a string array into a map (an odd index is key, even an index is a value)

Now I have an array of String,

String[] a= {"from","a@a.com","to","b@b.com","subject","hello b"};

from command line arguments.

I want to convert it to Map,

{"from":"a@a.com","to":"b@b.com","subject":"hello b"}

Is there a convenient way in java8 to achieve this? Now my way

Map<String,String> map = new HashMap<>();
for (int i = 0; i < args.length; i+=2) {
    String key = args[i].replaceFirst("-+", ""); //-from --> from
    map.put(key, args[i+1]);
}
+4
source share
4 answers

You can use IntStreamto iterate over the indices of the array (which is required to process two elements of the array each time) and use the collection Collectors.toMap.

IntStreamwill contain the corresponding index for each pair of elements in the input array. If the length of the array is odd, the last element will be ignored.

Map<String,String> map = 
    IntStream.range(0,a.length/2)
             .boxed()
             .collect(Collectors.toMap(i->a[2*i].replaceFirst("-+", ""),
                                       i->a[2*i+1]));
+10
source

Java 8 Stream.iterate 2

    String[] a= {"from","a@a.com","to","b@b.com","subject","hello b"};

    Map<String, String> map = Stream.iterate(
        Arrays.asList(a), l -> l.subList(2, l.size()))
            .limit(a.length / 2)
            .collect(Collectors.toMap(
                l -> l.get(0).replaceFirst("-+", ""),
                l -> l.get(1))
            );

Iterator

Map<String, String> map = buildMap(new HashMap<>(), Arrays.asList(a).iterator());

private static Map<String, String> buildMap(
        Map<String, String> map, Iterator<String> iterator) {
    if (iterator.hasNext()) {
        map.put(iterator.next().replaceFirst("-+", ""), iterator.next());
        createMap(map, iterator);
    }
    return map;
}
+1

Javaslang:

String[] a= {"from","a@a.com","to","b@b.com","subject","hello b"};

Map<String, String> map = Stream.of(a).grouped(2) // use javaslang.collection.Stream here
  .map(group -> group.toJavaArray(String.class))
  .toJavaStream() // this is the plain old java.util.Stream
  .collect(toMap(tuple -> tuple[0], tuple -> tuple[1]));

grouped . , Map. , Javaslang .

+1

, , /, :

Map<String,String> map = Arrays.stream(
    String.join(",", a)
          .split(",(?!(([^,]*,){2})*[^,]*$)"))
          .map(s -> s.split(","))
          .collect(Collectors.toMap(s -> s[0], s -> s[1]))
          ;
0

Source: https://habr.com/ru/post/1622427/


All Articles