skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Tuesday, October 16, 2012

Splitting the Elements in One Array and Adding into Map based on Length in Second Array

Posted by Raju Gupta at 9:00 AM – 0 comments
 
The Code Snippet will split the array elements using Comma and add this into List. After this it will add the id value as key and extract the SubList from the parentList, adding the SubList as value based on the length from a different array.

/**
  * @param args
  * 
  */
 public static void main(String[] args){
  
  String[] array = {"23,29,1", "3,36,1", "13,43,1", "15,50,1", "23,57,1", "23,64,1", "23,71,1", "23,78,1", "23,85,1", "23,92,1", "23,99,1"};
  String[] arraySize = {"6", "5"};
  String[] idKey = {"29", "30"};
  
  //Initialising List holds the values for all sections
  List<String> averageList = new ArrayList<String>();
  //Initialising sectionMap idKey and averageList values as key and value pairs. 
  HashMap<String, List> sectionMap = new HashMap<String, List>();
  //Iterate the Array to split the elements using Comma
  for (String average: array){
   String[] details = average.split(",");
   averageList.add(details[0]); 
  } 
  
  int endIndex = 0;
  int beginIndex = 0;
  /* Iterate the arraySize to add idKey 
   * and averageList values as key and value pairs. 
   */ 
  for(int i=0; i<arraySize.length; i++){
   if (i==0){
    beginIndex = 0;
    //Assigning the endIndex from the arraySize
    endIndex = new Integer(arraySize[i]);
    //Adding the idKey and extracting the subList from the averageList into sectionMap
    sectionMap.put(idKey[i], averageList.subList(beginIndex, endIndex));
   }else {
    //Assigning endIndex as beginIndex for i>0
    beginIndex = endIndex;
    endIndex = endIndex + new Integer(arraySize[i]);
    sectionMap.put(idKey[i], averageList.subList(beginIndex, endIndex));
   }
  }
  System.out.println("sectionMap -->" +sectionMap);
 }

Labels: Array Example , Java Map Example

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger