import java.util.*; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter the number of address:"); int n = scanner.nextInt(); scanner.nextLine(); // Consume newline left-over Map<String, Map<String, Integer>> map = new HashMap<>(); for (int i = 0; i < n; i++) { System.out.println("Enter the address:"); String[] address = scanner.nextLine().split(","); String state = address[2]; String city = address[1]; if (!map.containsKey(state)) { map.put(state, new HashMap<>()); } if (!map.get(state).containsKey(city)) { map.get(state).put(city, 0); } map.get(state).put(city, map.get(state).get(city) + 1); } List<String> states = new ArrayList<>(map.keySet()); Collections.sort(states); System.out.println("Number of entries in city/state wise:"); for (String state : states) { System.out.println("State:" + state); List<String> cities = new ArrayList<>(map.get(state).keySet()); Collections.sort(cities); for (String city : cities) { System.out.println("City:" + city + " Count:" + map.get(state).get(city)); } System.out.println(); } } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter