Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java8 convert string array to map(odd index is key, even index is value)

Tags:

java

java-8

Now I have a String array,

String[] a= {"from","[email protected]","to","[email protected]","subject","hello b"};

from command line arguments.

I want to convert it to Map,

{"from":"[email protected]","to":"[email protected]","subject":"hello b"}

Does exist convenient manner in java8 to achieve this? Now my way is

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]);
}
like image 969
zhuguowei Avatar asked Dec 05 '22 19:12

zhuguowei


1 Answers

You can use an IntStream to iterate on the indices of the array (which is required in order to process two elements of the array each time) and use the Collectors.toMap collector.

The IntStream will contain a corresponding index for each pair of elements of 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]));
like image 63
Eran Avatar answered Dec 25 '22 23:12

Eran