Apex String Array – Looping Through String Array and Splitting Elements

I have a list<string> that contains a list of elements like this

element_a, element_b, element_c, element_d

and that is easy enough to deal with,

 for(String elements : ELEMENTS_ARRAY) {   }

but I on occasion have a list<string> like this

element_a, element_b 3, element_c, element_d

I am trying to figure how how to deal with an array where a value contains a space followed by a number and then return the element_b with the number as two separate values.

Best Answer

Map<String, Integer> tempMap = new Map<String, Integer>();
for(String element : ELEMENTS_ARRAY) {  
      if(element.contains(’ ’){
           tempMap.put(element.split(’ ’).get(0), Integer.valueOf(element.split(’ ’).get(1));
      }
 }

Then return the map and use the key as the element and its value as the number

Related Topic