Help the bookseller !
Solution:
import java.util.*;
public class StockList{
public static String stockSummary(String[] lstOfArt, String[] lstOf1stLetter){
if(lstOfArt == null || lstOfArt.length == 0){
return "";
}
Map<String,Integer> map = new HashMap<String,Integer>();
for(String x : lstOfArt){
String[] arr = x.split(" ");
String c = x.substring(0,1);
if(map.containsKey(c)){
map.put(c,map.get(c) + Integer.valueOf(arr[1]));
}else{
map.put(c,Integer.valueOf(arr[1]));
}
}
StringBuilder sb = new StringBuilder();
for(int i = 0; i < lstOf1stLetter.length; i++){
Integer count = map.containsKey(lstOf1stLetter[i]) ? map.get(lstOf1stLetter[i]) : 0 ;
if(i != lstOf1stLetter.length - 1){
sb.append(String.format("(%s : %d) - ",lstOf1stLetter[i],count));
}else{
sb.append(String.format("(%s : %d)",lstOf1stLetter[i],count));
}
}
return sb.toString();
}
}
Example Test:
import static org.junit.Assert.*;
import org.junit.Test;
public class StockListTest{
@Test
public void test1(){
String art[] = new String[]{"ABAR 200","CDXE 500","BKWR 250","BTSQ 890","DRTY 600"};
assertEquals("(A : 200) - (B : 1140)", StockList.stockSummary(art, cd));
}
}