I have to take input from the user in CSV format (area,city,state, pincode). I have created Map<String, Map<String, Integer>>
. Output should have State name in the first line and each city name along with the count of address in the city in the next lines. A sample of input and output is like in the added image.
Input and Output Sample Picture
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
public class Main {
public static void main(String args[]) throws IOException {
Map<String, Map<String, Integer>> address1 = new LinkedHashMap<String, Map<String, Integer>>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of address:");
int n = Integer.parseInt(br.readLine());
for(int i = 1; i <= n; i++) {
Map<String, Integer> address2 = new LinkedHashMap<String, Integer>();
System.out.println("Enter the address:");
String input[] = br.readLine().split(",");
if(address2.containsKey(input[1])) {
address2.replace(input[1], (address2.get(input[1]) + 1));
}
else {
address2.put(input[1], 1);
}
address1.put(input[2], address2);
}
br.close();
System.out.println("Number of entries in city/state wise:");
ArrayList<Object> data = new ArrayList<Object>(address1.keySet());
ArrayList<Object> data2 = new ArrayList<Object>(address1.values());
for(int i = 0; i < address1.size(); i++) {
Object obj = data.get(i);
System.out.println("State:" + obj + "\n");
for(int j = 0; j < data2.size(); j++) {
Object obj2 = data2.get(j);
System.out.print("City:" + obj2 + "\n");
}
}
}
}