Computer Science 15-110, Fall 2009
Class Notes: The JCF, Part 1: Lists, Sets, and Maps
import java.util.*;
import java.io.*;
class FileAndSetDemo {
public static HashSet<String> diff(HashSet<String> set1,
HashSet<String> set2) {
HashSet<String> diff = new HashSet<String>();
for (String s : set1)
if (!set2.contains(s))
diff.add(s);
return diff;
}
public static HashSet<String> getDir(String dirName) {
File dir = new File(dirName);
HashSet<String> set = new HashSet<String>();
String[] files = dir.list();
for (String file : files)
set.add(file);
return set;
}
public static void main(String[] args) {
HashSet<String> fileSet1 = getDir("dir1");
HashSet<String> fileSet2 = getDir("dir2");
System.out.println("Files in dir1 but not in dir2:");
System.out.println(diff(fileSet1, fileSet2));
System.out.println("Files in dir2 but not in dir1:");
System.out.println(diff(fileSet2, fileSet1));
}
}
import java.util.*;
class SetsAndMapsDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("******************************");
System.out.println("Set Demo");
System.out.println("******************************");
HashSet<String> set = new HashSet<String>();
while (true) {
System.out.print("Enter a string (or 'q' to quit Set demo / start Map demo): ");
String s = scanner.next();
if (s.equals("q")) break;
System.out.println(" set.contains(" + s + ") = " + set.contains(s));
set.add(s);
}
System.out.println();
System.out.println("******************************");
System.out.println("Map Demo");
System.out.println("******************************");
HashMap<String,Integer> map = new HashMap<String,Integer>();
while (true) {
System.out.print("Enter a string (or 'q' to quit): ");
String s = scanner.next();
if (s.equals("q")) break;
// Integer iInt = map.get(s);
// int i = ((iInt == null) ? 0 : iInt);
int i = ((map.keySet().contains(s)) ? map.get(s) : 0);
System.out.println(" You entered '" + s + "' " + (i+1) + " time(s).");
map.put(s, i+1);
}
}
}
carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem