Main
class Foo {
public static void main(String[] args) {
// actions here
}
}
Lists
Create a new list with elements:
ArrayList<Integer> myList = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
Operations
.set(5, "thing") - to replace an item
.add("mango") - to add an item
.add(3, "foo") - add an item before an index, making it the new index for the new item
.remove("apple") - finds and removes
.remove(0) - remove an element by index
.get(0) - get an item at index
.subList(startIndex, endIndexPlusOne)
.addAll(otherList) - add list to existing list
.indexOf("thing")
Arrays
Create a new array with elements:
String[] fruit = {"kiwi", "lemon", "mango"};
To List
ArrayList<String> fruitList = new ArrayList<>(Arrays.asList(fruit));
List to Array
String[] newArray = fruitList.toArray(new String[0]);
Print an array
System.out.println(Arrays.toString(scores));
Size of array
int size = scores.length;
Sorting
Lists
myList.sort();
myList.sort(Collections.reverseOrder());
Collections.sort(taskIds);
Custom Comparator
implements Comparable
@Override
public int compareTo(Person other) {
int ageCompare = Integer.compare(this.age, other.age);
if (ageCompare != 0) {
return ageCompare;
}
return this.name.compareTo(other.name);
}
also need equals() and hashcode()
Sort list of Maps
list.sort(Comparator.comparing(map -> (Integer) map.get("score")));
Sort Objects
list.sort(Comparator.comparing(Post::createDate));
Strings
Get Character in String
content.charAt(2)
Common Operations
.toLowerCase()
.toUpperCase()
.trim() - trims from front and back
Iteration
content.toCharArray() // can use to iterate a string
for (char ch : word.toCharArray()) {
}
Substring
content.subString(startIndex, endIndexPlusOne);
Splitting a String
content.split(" ") // returns String[]
// better:
StringTokenizer tokenizer = new StringTokenizer(sentence, " ");
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
}
Character
To get ASCII
char c = 'A';
int ascii = (int) c;
ASCII to Char
int ascii = 65;
char c = (char) ascii;
Common Operations
Character.toUpperCase(c);
Character.toLowerCase(c);
Character.isUpperCase(a)
Character.isLowerCase(b)
Character.isLetter()
Character.isDigit()
Character.isLetterOrDigit()
StringBuilder
StringBuilder db = new StringBuilder("Hello");
sb.append(", world!");
sb.insert(5, ","); // insert at a specific location, like add() for lists
sb.length()
sb.charAt(5)
sb.reverse() // reverse that string!
sb.toString() // to concatenate the string for use
String Streams
String result = stringList.stream().collect(Collectors.joining());
String Type Conversion
String numStr = "123";
int num = Integer.parseInt(numStr); // throws NumberFormatException
String floatStr = "12.34";
float num = Float.parseFloat(floatStr);
int age = 20;
String ageStr = String.valueOf(age);
Maps
Common Operations
myMap.put(key, value)
myMap.putIfAbsent(key, new ArrayList<>()) // great for initialization
myMap.getOrDefault(key, default)
// together:
myMap.put(key, myMap.getOrDefault(key, 0) + 1)
// merge with sum
users.get(userId).merge(activityType, distance, Integer::sum);
// iterate:
for (Map.Entry entry, myMap.entrySet()) {
entry.getKey()
entry.getValue()
}
// Example: using computeIfAbsent to lazily create a list
Map<String, List<Integer>> map = new HashMap<>();
map.computeIfAbsent("numbers", k -> new ArrayList<>()).add(42);
Rounding
Math.round() // only rounds to an integer
// as a string:
String meanRounded = String.format("%.2f", mean);
// as a double:
double meanRounded = Math.round(mean * 100.0) / 100.0;
Formatting
Numbers
%.2f - 2 decimal places (for float)
%02d - 0 padded digits (for int)
Reading/Writing Files
Reading All or Line By Line
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
Path filePath = Paths.get("example.txt");
// all at once
String content = Files.readString(filepath);
// Reading line by line:
List<String> lines = Files.readAllLines(path);
for (String line: lines) {
// do something
}
Reading character by character
import java.io.FileReader;
FileReader reader = new FileReader(filePath.toFile());
int charInt = reader.read();
reader.close();
Writing and appending
Files.write(outputPath, content.getBytes());
Files.write(outputPath, content.getBytes(), StandardOpenOption.APPEND);
Jackson & CSV
Numbers
// alterate way to make a file (for csv reading)
File file = new File(filename);
//read
CsvMapper csvMapper = new CsvMapper();
CsvSchema schema = CsvSchema.emptySchema().withHeader();
List<Map<String, String>> data;
MappingIterator<Map<String, String>> iterator = csvMapper
.readerFor(Map.class)
.with(schema)
.readValues(filePath.toFile());
Map Objects
MappingIterator<Car> iterator = csvMapper.readerFor(Car.class)
.with(csvSchema)
.readValues(csvFile);
data = iterator.readAll();
OR
while (iterator.hasNext()) {
Car car = iterator.next();
...
}
Write CSV
CsvMapper mapper = new CsvMapper();
CsvSchema schema = csvMapper.schemaFor(Person.class).withHeader();
csvMapper.writer(schema).writeValue(outputFilePath.toFile()), data);
BufferedWriter
import java.io.BufferedWriter;
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath.toFile()));
writer.write("Name\tAge\Occupation\n");
writer.close();
JSON
Reading with Jackson
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
ObjectMapper objectMapper = new ObjectMapper();
try {
JsonNode rootNode = objectMapper.readTree(json);
} catch (IOException e) {
}
String prettyJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode);
System.out.println(prettyJson);
Accessing JSON
String schoolName = rootNode.path("school").asText();
String city = rootNode.path("location").path("city").asText();
string secondStudentName = rootNode.path("students").get(1).path("name").asText();
// other path operations
.asText()
.asInt()
.toString() - to get an entire node as a string to map it to an object
// test for missing nodes
.path("foo").isMissingNode();
Writing JSON
import com.fasterxml.jackson.annotation.JsonProperty;
public class Participant {
@JsonProperty("participantName")
private String name;
}
String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(company);
Files.write(outputFilePath, jsonString.getBytes());
// mapping to objects
Company company = mapper.readValue(json, Company.class);
ZIP Files
Reading files
import java.util.zip.ZipFile;
import java.util.zip.ZipEntry;
ZipFile zipFile = new ZipFile(zipFilePath.toFile());
var entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry = entries.nextElement();
entry.getName(); // name of file
}
Get a specific File
ZipEntry entry = zipFile.getEntry("data.txt");
if (entry != null) {
// it exists
}
zipFile.close();
Reading from a Zip File
import java.util.Scanner;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
InputStream stream = zipFile.getInputStream(entry);
Scanner scanner = new Scanner(stream, StandardCharSets.UTF_8.name());
while (scanner.hasNext()) {
if (scanner.hasNextInt()) { // read int from file
sum += scanner.nextInt();
} else {
scanner.next();
}
}
scanner.close();
stream.close();
Writing a Batch
Parsing CSV files can be done with third‑party libraries (OpenCSV, Apache Commons CSV) or Java 8 streams. Handle headers, delimiters, and escaping as needed.
CsvSchema schema = CsvSchema.emptySchema().withoutHeader();
SequenceWriter writer = csvMapper.writer(schema).writeValues(file);
writer.writeAll(rows);
writer.close();
// count lines
Files.lines(path).count();
APIs
gson requires an update to pom/build file
HttpClient client = HttpClient.new HttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + "/todos"))
.GET()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
response.body();
response.statusCode()
Gson gson = new Gson();
Type todoListType = new TypeToken>() {}.getType();
List<Todo> todos = gson.fromJson(getResponse.body(), todoListType);
// OR
Todo todo = gson.fromJson(response.body(), Todo.class);
for errors:
var error = JsonParser.parseString(response.body()).getAsJsonObject();
POST
Todo newTodo = new Todo("Learn Java", "Complete a course.", false);
String requestBody = gson.toJson(newTodo);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(BASE_URL + "/todos"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
PUT
Map<String, Object> updatedTodo = Map.of(
"title", "Buy groceries and snacks",
"done", true,
"description", "Milk, eggs, bread, coffee, and chips."
);
PATCH
Map<String, Object> patchData = Map.of("description", "Updated description");
good responses for methods
GET, PUT, PATCH 200
POST 201
DELETE 204 (sometimes 200, check API docs)
errors
Throw IOException for failures
throw new IOException("404 Not found");
throw new IOException("400 Bad request: " + response.body());
for network issues, wrap in try catch
try {
client.send(request, HttpResponse.BodyHandlers.ofString());
} catch (IOException e) {
System.out.println("Other error occurred: Unable to connect to the server.");
} catch (InterruptedException e) {
System.out.println("Other error occurred: Request was interrupted.");
}
downloading (small files)
HttpResponse<byte[]> response = client.send(request, HttpResponse.BodyHandlers.ofByteArray());
// Check if request was successful
if (response.statusCode() == 200) {
// Save file locally
Path filePath = Paths.get("downloaded_" + noteName);
Files.write(filePath, response.body());
}
efficient downloading
HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
// Handle response for successful download
if (response.statusCode() == 200) {
Path path = Paths.get("downloaded_" + noteName);
try (InputStream inputStream = response.body();
FileOutputStream fileOutputStream = new FileOutputStream(path.toFile())) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
}
}
try with resources
try (BufferedReader reader = new BufferedReader(new FileReader(noteName))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("File error occurred: " + e.getMessage());
}
uploads
Path filePath = Paths.get("file.txt");
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://example.com/upload"))
.header("Content-Type", "multipart/form-data;boundary=boundary")
.POST(ofMimeMultipartData(filePath))
.build();
private static HttpRequest.BodyPublisher ofMimeMultipartData(Path filePath) throws IOException {
var byteArrays = List.of(
"--boundary\r\n".getBytes(),
"Content-Disposition: form-data; name=\"file\"; filename=\"".getBytes(),
filePath.getFileName().toString().getBytes(),
"\"\r\nContent-Type: text/plain\r\n\r\n".getBytes(),
Files.readAllBytes(filePath),
"\r\n--boundary--\r\n".getBytes());
return HttpRequest.BodyPublishers.ofByteArrays(byteArrays);
}
Storing and using API Keys
String API_KEY = System.getenv("API_KEY");
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + "/todos"))
.header("X-API-Key", API_KEY)
.build();
Session-based auth
HttpClient client = HttpClient.newBuilder()
.cookieHandler(new CookieManager())
.build();
Log out
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(BASE_URL + "/auth/logout"))
.POST(HttpRequest.BodyPublishers.noBody())
.build();
// 401 Unauthorized when trying subsequent calls post-logout
JWTs
stateless, scalable, modern
login responds with:
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6",
"refresh_token": "15c8cbda2d99307391c160de1b8f2",
refresh_token allows you to get a new access_token
Sending JWT
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(BASE_URL + "/todos"))
.header("Authorization", "Bearer " + accessToken)
.build();
Refresh Token
refreshRequestJson.addProperty("refresh_token", refreshToken);
// just a regular POST to refresh endpoint
JWT Logout
// Send refresh_token in POST (using access_token) to logout endpoint
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(BASE_URL + "/auth/logout"))
.header("Authorization", "Bearer " + accessToken)
.POST(HttpRequest.BodyPublishers.ofString(logoutRequestBody))
.header("Content-Type", "application/json")
.build();
Stacks
import java.util.Stack;
Stack<String> stack = new Stack<>();
.push();
.pop();
.peek() - top entry
.empty() - boolean
Queue
Queue<String> q = new LinkedList<>();
q.add("foo");
q.poll();
q.isEmpty();
q.size()
Deque
Deque<String> d = new ArrayDeque<>();
d.addLast("Right end") // similar to adding to normal queue
d.addFirst("Left end")
d.removeLast()
d.removeFirst() // similar to polling normal queue
d.size()
Sorted Maps - TreeMap
TreeMap is a sorted map alphabetically by default. Does NOT keep order in which they were added.
TreeMap<String, Integer> treeMap = new TreeMap<>();
tm.put("banana", 3);
tm.put("apple", 4);
// use a custom comparator to order keys differently
Concurrency
Java offers a rich concurrency toolkit: threads, executors,
synchronized blocks, and the java.util.concurrent package. Use
CompletableFuture for async pipelines.
// Example: running tasks asynchronously with CompletableFuture
CompletableFuture.supplyAsync(() -> computeHeavyTask())
.thenApply(result -> processResult(result))
.exceptionally(ex -> handleError(ex));
Miscellaneous
Using a lambda with Stream API
List<String> names = List.of("Alice", "Bob", "Charlie");
names.stream()
.filter(n -> n.startsWith("A"))
.forEach(System.out::println); // Alice
Other
Collections.min(numberList);
Integer.MIN_VALUE
Integer.MAX_VALUE
Random rand = new Random();
rand.nextInt();
rand.nextInt(201) - upper bound exclusive ( goes to 200)
double average = (double) someInt / anotherInt;
if (printer instanceof Printer) {}
// convert Set to List
List<String> theList = new ArrayList<>(theSet);