Some people learn best through examples. With that in mind, here are some stripped-down simplified examples of Java code to perform various tasks. These snippets are not robust enterprise-ready patterns nor do they do not represent best practices. Rather, they are barebones examples to help you get up and running as quickly as possible.
Catalog of Java Snippets:
Elsewhere:
The snippets are presented as complete programs so you can quickly run and test them. For example, to try out the "HashMap Loop" example, 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 LoopHashMaps 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));
}
}
Color --> Green
Speed --> Fast
Size --> Medium
Program Output
TopMap Element TrackerThis 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 TopMap extends 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());
}
}
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).
XML WriterThis snippet creates a very simple DOM (Document Object Model) containing a list of countries and then writes the DOM out to an XML file.
XmlWriter.java
import java.io.File;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
public class XmlWriter {
public static void main(String[] args) {
try {
//Sample Data (countries and capitals)
HashMap data = new HashMap();
data.put("Egypt", "Cairo");
data.put("Finland", "Helsinki");
data.put("Japan", "Tokyo");
//Create DOM (with top-level node)
DocumentBuilder xmlBuilder =
DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document xmlDoc = xmlBuilder.newDocument();
Node node = xmlDoc.createElement("countries");
xmlDoc.appendChild(node); //top-level node
//Add Data to DOM
for (String key : data.keySet()) {
Element elem = xmlDoc.createElement("country");
elem.setAttribute("capital", data.get(key)); //attrib
elem.appendChild(xmlDoc.createTextNode(key)); //content
node.appendChild(elem);
}
//Write DOM to XML file
Source source = new DOMSource(xmlDoc);
Result result = new StreamResult(new File("countries.xml"));
Transformer xformer =
TransformerFactory.newInstance().newTransformer();
xformer.setOutputProperty(OutputKeys.INDENT, "yes");
xformer.transform(source, result);
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
countries.xml
<?xml version="1.0" encoding="UTF-8"?>
<countries>
<country capital="Helsinki">Finland</country>
<country capital="Cairo">Egypt</country>
<country capital="Tokyo">Japan</country>
</countries>
File Created by Program
Note that using a DOM holds the entire XML tree structure in memory. For large data sets it is often necessary to instead use SAX (Simple API for XML) which uses an event based approach to hold and process only the part of the document that is needed.
XML ValidatorThis snippet validates an XML file against an XSD (XML Schema Definition).
XmlValidator.java
import java.io.File;
import javax.xml.XMLConstants;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.transform.stream.StreamSource;
public class XmlValidator {
public static void main(String[] args) {
try {
StreamSource xsdInput = new StreamSource(new
XmlValidator().getClass().getResourceAsStream("countries.xsd"));
Schema schema = SchemaFactory.newInstance(
XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(xsdInput);
schema.newValidator().validate(new StreamSource(
new File("countries.xml")));
System.out.println("XML file sucessfully validated against XSD.");
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
XML Schema Used to Validate XML
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="countries">
<xs:complexType>
<xs:sequence>
<xs:element name="country" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="country">
<xs:complexType mixed="true">
<xs:attribute name="capital" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:schema>
cvc-complex-type.2.4.a: Invalid content was found starting
with element 'region'. One of '{"":country}' is expected.
Program Output
XML ReaderThis snippet reads an XML file and prints out the name of each node along with its first attribute.
XmlReader.java
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.*;
public class XmlReader {
static void processNode(Node node) {
String msg = "node --> " + node.getNodeName();
String nodeContent = node.getFirstChild().getNodeValue();
if (!nodeContent.equals("\n")) //check if has text content
msg = msg + " | value: " + nodeContent; //add text content
if (node.hasAttributes()) //add first attrib if exists
msg = msg + " | attrib: " +
node.getAttributes().item(0).getNodeName() + "=" +
node.getAttributes().item(0).getNodeValue();
System.out.println(msg); //display node information
for (Node subNode = node.getFirstChild(); subNode != null;
subNode = subNode.getNextSibling())
if (subNode.getNodeType() == Node.ELEMENT_NODE)
processNode(subNode);
}
public static void main(String[] args) {
try {
DocumentBuilder xmlBuilder =
DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document xmlDoc = xmlBuilder.parse(new File("countries.xml"));
processNode(xmlDoc.getDocumentElement());
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
node --> countries
node --> country | value: Finland | attrib: capital=Helsinki
node --> country | value: Egypt | attrib: capital=Cairo
node --> country | value: Japan | attrib: capital=Tokyo
Program Output (input file: countries.xml)
Web Page ReaderThis 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());
}
}
}
<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.