// This program reads a Graphviz graph file of friendships and prints the set // of friends for each person. import java.io.*; import java.util.*; public class Friends1 { public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("friends.dot")); Map> friends = readFile(input); for (String name : friends.keySet()) { System.out.printf("%-12s => maps to => %s\n", name, friends.get(name).toString()); } } // pre : input is open and contains a legal Graphviz file of friendship // connections where each friend is listed as a single token // post: returns a map that contains for each person the set of friends for // that person public static Map> readFile(Scanner input) { Map> friends = new TreeMap>(); while (input.hasNextLine()) { String line = input.nextLine(); if (line.contains("--")) { Scanner lineData = new Scanner(line); String name1 = lineData.next(); lineData.next(); // this skips the "--" token String name2 = lineData.next(); addTo(friends, name1, name2); addTo(friends, name2, name1); } } return friends; } // post: records a friendship for name1. If name1 is not in the map, a new // set is added to the map public static void addTo(Map> friends, String name1, String name2) { if (!friends.containsKey(name1)) { friends.put(name1, new TreeSet()); } friends.get(name1).add(name2); } }