$ cat LowGrades.java import java.io.InputStream; import java.io.PrintStream; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Scanner; import java.util.Vector; class LowGrades { private static Map in(Iterator triples) { final HashMap lowGrades = new HashMap(); while (triples.hasNext()) { final Triple t = triples.next(); if ( !lowGrades.containsKey(t.course) || lowGrades.get(t.course).studentID > t.studentID) lowGrades.put(t.course, t); } return lowGrades; } public static void main(String[] args) { out(System.out, in(new TripleIterator(System.in))); } private static void out(PrintStream outs, Map lowGrades) { final Vector keys = new Vector(lowGrades.keySet()); Collections.sort(keys); for (String key : keys) outs.printf("%s %d%n", key, lowGrades.get(key).grade); } private static class Triple { final int studentID; final String course; final int grade; Triple(int s, String c, int g) { studentID = s; course = c; grade = g; } } private static class TripleIterator implements Iterator { public boolean hasNext() { return scanner.hasNextInt(); } TripleIterator(InputStream ins) { scanner = new Scanner(ins); scanner.useDelimiter("[|\n]"); } public Triple next() { return new Triple(scanner.nextInt(), scanner.next(), scanner.nextInt()); } private final Scanner scanner; } } $ javac -Xlint LowGrades.java $ cat < 22|Math|45 > 23|English|52 > 22|English|51 > 26|Math|72 > 23|Math|61 > 21|English|81 > eot English 81 Math 45 $ echo this is a test | ./LowGradesData 14|this|14 20|a|20 4|this|4 22|a|22 26|test|26 17|is|17 2|is|2 1|a|1 26|test|26 28|a|28 20|is|20 13|test|13 10|a|10 4|test|4 16|is|16 12|is|12 8|test|8 6|this|6 3|is|3 18|test|18 7|test|7 11|is|11 15|this|15 12|a|12 $ echo lost my shape trying to act casual | ./LowGradesData | java LowGrades act 3 casual 6 lost 4 my 2 shape 5 to 2 trying 6 $