Skip to content

Commit 6d1c4b4

Browse files
committed
initial commit
0 parents  commit 6d1c4b4

14 files changed

+871
-0
lines changed

.gitignore

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
test_data.txt
2+
out/
3+
4+
# IntelliJ
5+
.idea/
6+
*.iml
7+
src/META-INF

README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# Executable Java Cheat Sheets
2+
3+
These are "executable Cheat Sheets" demonstrating some foundational Java syntax and commonly used classes.
4+

src/ArrayCheatSheet.java

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import java.util.Arrays;
2+
import java.util.List;
3+
4+
public class ArrayCheatSheet {
5+
public static void main(String[] args) {
6+
// Class reference: none
7+
// Tutorial: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
8+
// Language specification: http://docs.oracle.com/javase/specs/jls/se8/html/jls-10.html
9+
// Array Module: http://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Array.html
10+
// Arrays Module: http://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html
11+
12+
// Notes:
13+
// - can not change size of array in Java
14+
// - when passed into a method, the contents of an array are muteable
15+
16+
// basic
17+
int[] odds = {1, 3, 5, 7};
18+
System.out.println(odds); // prints out hash? id? pointer?
19+
System.out.println(Arrays.toString(odds)); // prints out items
20+
21+
// creation, initializatoin and literals
22+
int[] b = new int[3]; // initialized to zeros (null for String)
23+
int[] a = {1, 3, 5}; // array literal
24+
int[] evens = new int[]{2, 4, 6};
25+
System.out.println(new int[]{2, 4, 6, 8, 10}); // pass array literal to function
26+
27+
// indexing and assignment
28+
a[0] = 42; // assign to index
29+
int c = a[1]; // index into array
30+
b = a; // assigns each variable a reference to same data
31+
32+
// iteration
33+
for (int i = 0; i < a.length; ++i) {
34+
System.out.println(a[i]);
35+
}
36+
for (int val: a) {
37+
System.out.println(val);
38+
}
39+
40+
// copying
41+
int[] trg = new int[7];
42+
System.arraycopy(odds, 0, trg, 0, odds.length); // (src, srcStart, trg, trgStart, length)
43+
44+
// Multidimensional arrays
45+
// In Java, a multidimensional array is one whose components are themselves arrays
46+
int[][] grid = {
47+
{1, 2, 3, 4},
48+
{5, 6, 7, 8}
49+
};
50+
System.out.println(grid[1][3]); // [row][column]
51+
for (int[] row: grid) {
52+
for (int val: row) {
53+
System.out.println(val);
54+
}
55+
}
56+
// because Java arrays are "arrays-in-arrays", you can have ragged arrays
57+
int[][] ragged = {
58+
{1, 2, 3, 4, 5},
59+
{6, 7},
60+
{8, 9, 10}
61+
};
62+
63+
// Arrays module (see reference link above)
64+
// (compare, sort, fill, search, copy, toString, etc.)
65+
System.out.println(Arrays.toString(a));
66+
67+
// convert Array to List
68+
Integer[] x = {2, 4, 6, 8}; // List<T> must contain an object. Can't have List of primitive type.
69+
List<Integer> items = Arrays.asList(x); // returns a fixed-size list backed by the specified array
70+
System.out.println(x[1] + " " + items.get(1));
71+
x[1] = 999; // if you mutate backing array, you are also mutating the List
72+
System.out.println(x[1] + " " + items.get(1));
73+
}
74+
}

src/FileProcessingCheatSheet.java

Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
import java.io.*;
2+
import java.nio.file.*;
3+
import java.util.List;
4+
5+
public class FileProcessingCheatSheet {
6+
public static void main(String[] args) throws IOException {
7+
// Come up with the whole way to write text to a file, read from a file, manipulate path names, etc.
8+
// There are lots of way to do this. Do I want to touch on all of them? Pick one and run with it?
9+
// Remember, there was an issue in clipboard where it wasn't reading files with newlines as you would expect (platform independent newlines)
10+
11+
// FileReader/Writer are basic and only support writing characters and streams
12+
// Wrapping FileReader/Writer in BufferedReader/Writer adds buffering and line-oriented operations
13+
14+
// basic
15+
// PrintWriter is similar to System.out
16+
PrintWriter w = new PrintWriter("test_data.txt"); // could also use a BufferedWriter
17+
w.println("line one"); // OS-independent line separator
18+
w.printf("line %d%n", 2); // %n = OS-independent line separator
19+
w.println("line three");
20+
w.close();
21+
22+
BufferedReader i = new BufferedReader(new FileReader("test_data.txt"));
23+
String line;
24+
while ((line = i.readLine()) != null) { // .readline() consumes line terminator
25+
System.out.println("READ: " + line);
26+
}
27+
i.close();
28+
29+
// console (simple prompts for input)
30+
// (also see InputCheatSheet)
31+
Console c = System.console();
32+
if (c == null) {
33+
System.out.println("No console. Skipping consle sample code.");
34+
} else {
35+
String inp = c.readLine("Enter text here Mr. %s", "Smith"); // Can be string literal, or empty for no prompt
36+
System.out.println("Entered: " + inp);
37+
}
38+
39+
// write to a file (write vs append)
40+
PrintWriter appending = new PrintWriter(new FileWriter("test_data.txt", true));
41+
appending.println("New line appended"); // uses OS-independent line separator
42+
appending.printf("another line%n"); // %n - OS-independent line separator
43+
appending.println("final line");
44+
appending.close();
45+
46+
// Note: java.io is older (From Java 1.4) where java.nio is newer
47+
// - can use File.toPath() to convert from "old" to "new"
48+
// - java.nio.file.Path = core of file processing in Java
49+
// - java.nio.file.Path replaces java.io.File (from Java 1.7)
50+
// - file or directory corresponding to the Path might not exist
51+
// - operate on path itself and don't access filesystem
52+
// - Paths is a Path helper class
53+
// - java.nio.file.Files
54+
// - static methods that take Path's to read, write, and manipulate files and directories on filesystems.
55+
Path p1 = Paths.get("c:\\abc\\def");
56+
System.out.println(p1);
57+
// Path p1b = Paths.get("aa", "bb", "cc", "dd"); // relative path
58+
Path p1b = Paths.get("aa\\bb\\cc\\dd"); // relative path
59+
System.out.println(p1b.toAbsolutePath());
60+
Path p2 = Paths.get("\\aa\\bb\\cc\\dd");
61+
System.out.println(p2);
62+
System.out.println(p2.toString());
63+
System.out.println(p2.getFileName());
64+
System.out.println(p2.getParent());
65+
System.out.println(p2.getRoot()); // null if a relative path
66+
System.out.println(p2.getNameCount());
67+
System.out.println(p2.getName(0));
68+
System.out.println(p2.subpath(1, 3));
69+
System.out.println(p2.toUri());
70+
System.out.println(p2.resolve("ee.txt")); // joining two Paths
71+
System.out.println(p2.resolve(Paths.get("yy\\zz"))); // joining two Paths
72+
System.out.println(Paths.get("home").relativize(Paths.get("home\\sally\\bar"))); // Result: sally\bar
73+
p1.equals(p2);
74+
p1.startsWith(p2);
75+
p1.endsWith(p2);
76+
for (Path path_name: p2) {
77+
System.out.println("Path: " + path_name);
78+
}
79+
//
80+
Path tmp = Paths.get("test_data.txt");
81+
Files.exists(tmp);
82+
Files.notExists(tmp);
83+
Files.isReadable(tmp);
84+
Files.isWritable(tmp);
85+
Files.isExecutable(tmp);
86+
Files.size(tmp);
87+
Files.isDirectory(tmp);
88+
Files.isRegularFile(tmp);
89+
// Files.getLastModifiedTime(tmp);
90+
// Files.setLastModifiedTime(tmp, FileTime.from(10000L, TimeUnit.DAYS));
91+
92+
// read lines from a file
93+
List<String> lines = Files.readAllLines(tmp);
94+
for (String s: lines) {
95+
System.out.println("_" + s + "_");
96+
}
97+
98+
// stream interface to read lines from a file
99+
Files.lines(tmp)
100+
.filter(s -> s.startsWith("line"))
101+
.forEach(s -> System.out.println("*" + s + "*"));
102+
103+
Path tmp2 = Paths.get("temp2.txt");
104+
Path tmp3 = Paths.get("temp3.txt");
105+
Files.copy(tmp, tmp2);
106+
Files.move(tmp2, tmp3);
107+
Files.delete(tmp3);
108+
109+
Files.createDirectory(Paths.get("mytempdir"));
110+
Files.delete(Paths.get("mytempdir"));
111+
112+
// iterate over root directories in filesystem
113+
Iterable<Path> dirs = FileSystems.getDefault().getRootDirectories();
114+
for (Path p: dirs) {
115+
System.out.println(p);
116+
}
117+
118+
// iterate over directory
119+
try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get("src"))) {
120+
for (Path file : stream) {
121+
System.out.println("In src: " + file.getFileName());
122+
}
123+
}
124+
// iterate over directory with glob matching
125+
try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get("src"), "*.java")) {
126+
for (Path entry : stream) {
127+
System.out.println("Glob: " + entry.getFileName());
128+
}
129+
}
130+
}
131+
}
132+
133+
134+
/* IS THERE ANYTHING USEFUL IN HERE? I DELETED THIS FILE...
135+
# Java File IO Cheat Sheet
136+
137+
### Read text from a file
138+
139+
Files.readAllBytes()
140+
141+
File file = new File("mypath/myfile.txt");
142+
String dat = new String(Files.readAllBytes(file.toPath()));
143+
144+
Scanner
145+
146+
Scanner in = new Scanner(Paths.get("stuff.txt"));
147+
while (in.hasNextLine()) {
148+
System.out.println("LINE:" + in.nextLine());
149+
}
150+
151+
152+
### Write text to a file
153+
154+
Print Writer
155+
156+
PrintWriter out = new PrintWriter("stuff.txt");
157+
out.print("word");
158+
out.println("line");
159+
out.printf("f: %s %d\n", "hello", 42);
160+
out.close();
161+
162+
*/

src/InputCheatSheet.java

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import java.io.BufferedReader;
2+
import java.io.Console;
3+
import java.io.IOException;
4+
import java.io.InputStreamReader;
5+
import java.util.Scanner;
6+
7+
/** Reference: https://stackoverflow.com/a/26473083 */
8+
public class InputCheatSheet {
9+
public static void main(String[] args) throws IOException {
10+
// demonstrate different ways to read from stdin
11+
readFromScanner();
12+
readFromConsole();
13+
readFromBufferedReader();
14+
parsingExample();
15+
}
16+
17+
private static void readFromScanner() {
18+
System.out.print("Enter your name: ");
19+
Scanner scanner = new Scanner(System.in);
20+
String name = scanner.nextLine();
21+
System.out.println("NAME: " + name);
22+
}
23+
24+
/** Does not work when run from inside IntelliJ, System.console() returns null */
25+
private static void readFromConsole() {
26+
Console console = System.console();
27+
if (console != null) {
28+
String name = console.readLine("Enter your name: ");
29+
System.out.println("NAME: " + name);
30+
} else {
31+
System.out.println("ERROR: Console not supported");
32+
}
33+
}
34+
35+
private static void readFromBufferedReader() throws IOException {
36+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
37+
System.out.print("Enter your name: ");
38+
String name = br.readLine();
39+
System.out.println("NAME: " + name);
40+
}
41+
42+
private static void parsingExample() {
43+
System.out.print("Enter ids separated by commas: ");
44+
Scanner scanner = new Scanner(System.in);
45+
String line = scanner.nextLine();
46+
System.out.println("LINE: " + line);
47+
String[] tokens = line.split(",");
48+
for (String token : tokens) {
49+
System.out.println("Integer: " + Integer.valueOf(token));
50+
}
51+
}
52+
}

src/ListCheatSheet.java

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import java.util.ArrayList;
2+
import java.util.Arrays;
3+
import java.util.Collections;
4+
import java.util.List;
5+
6+
public class ListCheatSheet {
7+
public static void main(String[] args) {
8+
// Class Reference: http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#ArrayList--
9+
// Tutorial: http://docs.oracle.com/javase/tutorial/collections/interfaces/list.html
10+
// Collections Framework Overview (with nice chart of all classes): http://docs.oracle.com/javase/8/docs/technotes/guides/collections/overview.html
11+
12+
// basic
13+
List<Integer> a = new ArrayList<>(); //
14+
a.add(42);
15+
a.add(99);
16+
System.out.println(a);
17+
18+
// creation, initialization and literals
19+
Integer[] blah = {1, 2, 3};
20+
ArrayList<Integer> b = new ArrayList<>(Arrays.asList(blah));
21+
ArrayList<Integer> c = new ArrayList<>(Arrays.asList(1, 2, 3));
22+
ArrayList<Integer> d = new ArrayList<>(Arrays.asList(new Integer[]{2, 4, 6, 8}));
23+
d.addAll(c);
24+
ArrayList<Integer> clone = (ArrayList<Integer>)d.clone(); // requires cast?
25+
b.clear();
26+
List<Integer> testList = new ArrayList(); // lists are often created this way...
27+
List<Integer> nums = Arrays.asList(2, 4, 6, 8); // be careful as this is an array-backed, quasi-immuteable, special List
28+
List<String> strings = Arrays.asList("abc", "def", "ghi");
29+
List<String> arguments = Arrays.asList(args); // convert args array to List
30+
//List<Integer> blah = List.of(2, 4, 6); // Java 9 (shorter, safer)
31+
32+
// accessing
33+
d.isEmpty();
34+
d.size();
35+
d.get(3);
36+
d.contains(42);
37+
d.indexOf(6); // first index where object is found, otherwise -1
38+
List<Integer> blah2 = d.subList(1, 3);
39+
blah2.set(1, 1243);
40+
41+
// mutate
42+
d.set(1, 99); // set index 1 to value 99
43+
d.remove(2); // by index
44+
d.remove((Integer)8); // by value (cast used to force use of the Object overload
45+
d.removeAll(a); // removes all items in a from d
46+
d.removeIf(v -> v % 3 == 0);
47+
d.sort(Integer::compareTo); // should be able to drop the comparator argument in Java 8?
48+
Collections.sort(d);
49+
d.replaceAll(v -> v + 100); // replaces all elements with result of function (UnaryOperator, lambda, etc.)
50+
51+
// iterating
52+
for (int i = 0; i < a.size(); ++i) {
53+
System.out.println(a.get(i));
54+
}
55+
for (Integer val: a) {
56+
System.out.println(val);
57+
}
58+
a.forEach(val -> {
59+
System.out.println(val);
60+
});
61+
62+
//////// conversion
63+
64+
// List to Array
65+
List<String> z = Arrays.asList("Beatrice", "Gerty", "Floyd");
66+
String[] other = new String[z.size()];
67+
String[] conv = z.toArray(other);
68+
}
69+
}

0 commit comments

Comments
 (0)