Lab 6: Using split

 

Using split


import java.util.*; 

public class Main {
  public static void main(String[] args) {
  
  // ArrayList to store product info in Hashmap for ListView 
  
  
  ArrayList<HashMap<String, String>> productsList = new ArrayList<HashMap<String, String>>();
  
  String result= "1;Long-grain rice, not parboiled, WKB;88.00:7;Pineapple King;19.00:11;Oat Bran;1.00:12;Apple;20.00:14;Soya Bean;2.00:";
  
  
  System.out.println(result+"\n\n");
  
  
  String[] products = result.split(":");
  
   for (int i=0; i<products.length; i++)
   {
        //System.out.println(products[i]);
        String[] details = products[i].split(";");
        String id = details[0]; 
        String name = details[1]; 
        String price = details[2];
        
        System.out.println("id: "+id+" name: "+name+ " price: "+price);
        
        HashMap<String, String> map = new HashMap<String, String>(); 
        // adding each product info to HashMap key-value pair 
        map.put("product_id", id); 
        map.put("product_name", name); 
        map.put("product_price", price);
        productsList.add(map);
}
   System.out.println(productsList);
} }

Output

1;Long-grain rice, not parboiled, WKB;88.00:7;Pineapple King;19.00:11;Oat Bran;1.00:12;Apple;20.00:14;Soya Bean;2.00:


id: 1 name: Long-grain rice, not parboiled, WKB price: 88.00
id: 7 name: Pineapple King price: 19.00
id: 11 name: Oat Bran price: 1.00
id: 12 name: Apple price: 20.00
id: 14 name: Soya Bean price: 2.00
[{product_id=1, product_price=88.00, product_name=Long-grain rice, not parboiled, WKB}, {product_id=7, product_price=19.00, product_name=Pineapple King}, {product_id=11, product_price=1.00, product_name=Oat Bran}, {product_id=12, product_price=20.00, product_name=Apple}, {product_id=14, product_price=2.00, product_name=Soya Bean}]

Comments

Popular posts from this blog

Simple Login Example (PHP Server + Android Client)