Catalog of Java Snippets:
The snippets are presented as complete programs so you can quickly run and test them.
For example, to try out the "HashMap Loop" program, you would download the
HashMapLoop.java file and execute the following commands:
$ javac *.java
$ java HashMapLoop.class
Code here is Public Domain Software — free to use as you like.HashMap Loop
HashMaps are convenient for storing key-value pairs. This snippet iterates over a java.util.HashMap collection without explicitly creating an iterator.
HashMapLoop.java
import java.util.HashMap;
public class HashMapLoop {
public static void main(String[] args) {
HashMap<String, String> data = new HashMap<String, String>();
data.put("Color", "Green");
data.put("Size", "Medium");
data.put("Speed", "Fast");
for (String key : data.keySet())
System.out.println(key + " --> " + data.get(key));
}
}
View/Download: HashMapLoop.java
Color --> Green Speed --> Fast Size --> Medium
Program Output
TopMap Element Tracker
This snippet keeps track of the top (heaviest, furthest, oldest, longest, loudest, fastest, etc.) elements as your program processes the elements. Instead of holding onto all the elements, this snippet uses java.util.TreeMap to hold only the top elements.
The code below demonstrates TopMap with a simple example of tracking the largest islands by land mass.
TopMap.java
import java.util.*; public class TopMapextends TreeMap { private final int maxElems; public TopMap(int maxNumberElements) { super(Collections.reverseOrder()); maxElems = maxNumberElements; } @Override public V put(Integer key, V value) { if (size() < maxElems || key > lastKey()) super.put(key, value); if (size() > maxElems) remove(lastKey()); return value; } public static void main(String[] args) { TreeMap islands = new TopMap (3); islands.put( 507000, "Baffin"); islands.put( 726000, "Borneo"); islands.put(2131000, "Greenland"); islands.put( 578000, "Madagascar"); islands.put( 800000, "New Guinea"); System.out.println("Three Largest Islands:"); for (Map.Entry island : islands.entrySet()) System.out.println(island.getKey() + " sq km - " + island.getValue()); } }
View/Download: TopMap.java
Three Largest Islands: 2131000 sq km - Greenland 800000 sq km - New Guinea 726000 sq km - Borneo
Program Output
Note that this solution does not support duplicates because TreeMap itself does not support duplicates. If your data contains ties (where two or more keys are equal), use TopMultiMap (which incorporates a special comparator to hide duplicates) or use TopElements (which incorporates lists to keep track of possible ties).
Web Page Reader
This snippet reads the contents of a web page (example: WebPageReader.html).
WebPageReader.java
import java.io.*;
import java.net.*;
public class WebPageReader {
public static void main(String[] args) {
String url = "http://www.centerkey.com/files/snippets/WebPageReader.html";
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(new URL(url).openStream()));
for (String s = reader.readLine(); s != null; s = reader.readLine())
System.out.println(s);
reader.close();
}
catch (Exception e) {
System.out.println(e.toString());
}
}
}
View/Download: WebPageReader.java
<html> <head><title>Simple Web Page</title></head> <bogy><h1>WebPageReader Test</h1></body> </html>
Program Output
This approach can also be used to read text data, such as a product's current version number, from a web site.
Desktop Browser Launch
This snippet opens a web page in the user's default browser.
DesktopBrowser.java
public class DesktopBrowser {
public static void main(String[] args) {
String url = "http://www.google.com";
try {
java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));
}
catch (java.io.IOException e) {
System.out.println(e.getMessage());
}
}
}
View/Download: WebPageReader.java
This code requires Java 6 or later.
Further Reading
Elsewhere:

