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]);
}
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]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With