Java Cheet sheet


1. Print Hello World

Print a literal string on standard output

System.out.println("Hello World");

2. Print Hello 10 times

Loop to execute some code a constant number of times

for(int i=0;i<10;i++)
  System.out.println("Hello");

3. Create a procedure

Like a function which doesn’t return any value, thus has only side effects (e.g. Print to standard output)

void finish(String name){
  System.out.println("My job here is done. Goodbye " + name);
}

void means “no return value”.

4. Create a function which returns the square of an integer

int square(int x){
  return x*x;
}

5. Create a 2D Point data structure

Declare a container type for two floating-point numbers x and y

class Point{
  double x;
  double y;
}

6. Iterate over list values

Do something with each item x of an array-like collection items, regardless indexes.

for(Item x : items ){
	doSomething( x );
}

This syntax is allowed since Java 5.

It works with arrays or collections as well.

Alternative implementation

for(int i=0;i<items.length;i++){
	doSomething( items[i] );
}

This syntax is now “old-school” since the foreach construct introduced in Java 5.

items.stream().forEach(item -> doSomething(item));

This syntax uses the streams api introduced in Java 8.

7. Iterate over list indexes and values

Print each index i with its value x from an array-like collection items

for (int i = 0; i < items.length; i++) {
    T x = items[i];
    System.out.printf("Item %d = %s%n", i, x);
}

items is an array.

Alternative implementation

for (int i = 0; i < items.size(); i++) {
    T x = items.get(i);
    System.out.printf("Item %d = %s%n", i, x);
}

items is a List.

for (int x; x < list.size(); x++) {
	System.out.println("index " + x + " value " + list.get(x));
}

8. Initialize a new map (associative array)

Declare a new map object x, and provide some (key, value) pairs as initial content.

import java.util.Map;
import java.util.HashMap;
Map<String,Integer> x = new HashMap<>();
x.put("one", 1);
x.put("two", 2);

Alternative implementation

import java.util.Map;
import java.util.HashMap;
final Map<String, Integer> x = new HashMap<String, Integer>() {{
    put("one", 1);
    put("two", 2);
    put("three", 3);
}};

9. Create a Binary Tree data structure

The structure must be recursive because left child and right child are binary trees too. A node has access to children nodes, but not to its parent.

class BinTree<T extends Comparable<T>>{
   T value;
   BinTree<T> left;
   BinTree<T> right;
}

Note that with this design an empty tree is null, and thus is not an instance of BinTree.

10. Shuffle a list

Generate a random permutation of the elements of list x

import java.util.Collections;
Collections.shuffle(x);

Already implemented in standard library.

This method alters the list.

If you need predictable results, see shuffle(List<?>, Random).

11. Pick a random element from a list

List x must be non-empty.

x.get((int)(Math.random()*x.size()))

Consider reusing the Random object, don’t create it each time you pick an element.

Alternative implementation

import java.util.concurrent.ThreadLocalRandom;
x.get(ThreadLocalRandom.current().nextInt(0, x.size()))

Using ThreadLocalRandom prevents unnecessary allocation of a new Random, and is more efficient in a multi-threaded application

12. Check if list contains a value

Check if list contains a value x.

list is an iterable finite container.

boolean contains(int[] list, int x){
  for(int y:list)
    if( y==x )
      return true;
  return false;
}

This applies to an array of primitive values, e.g. int

Alternative implementation

boolean <T> contains(T[] list, T x){
  if( x==null){
    for(T y:list)
      if( y==null )
        return true;
  }else{
    for(T y:list)
      if( x.equals(y) )
        return true;
  }
  return false;
}

This applies to an array of any non-primitive type T

import java.util.List;
list.contains(x)

This applies to any List

13. Iterate over map keys and values

Print each key k with its value x from an associative array mymap

for (Map.Entry<Object, Object> entry : mymap.entrySet()) {
    Object k = entry.getKey();
    Object x = entry.getValue();
    System.out.println("Key=" + k + ", Value=" + x);
}

Instead of Object, prefer using sensible key type and value type for your map.

14. Pick uniformly a random floating point number in [a..b)

Pick a random number greater than or equals to a, strictly inferior to b. Precondition : a < b.

import java.util.Math;
double pick(double a, double b){
	return a + (Math.random() * (b-a));
}

15. Pick uniformly a random integer in [a..b]

Pick a random integer greater than or equals to a, inferior or equals to b. Precondition : a < b.

import java.util.Random;
int pick(int a, int b){
	return a + new Random().nextInt(b - a + 1);
}

For performance, consider reusing the Random object.

(b-a+1) is needed to have upper bound b included.

16. Depth-first traversing of a binary tree

Call a function f on every node of binary tree bt, in depth-first infix order

void dfs(BinTree bt) {
	if (bt.left != null) {
		dfs(bt.left);
        }
	f(bt);
	if (bt.right != null) {
		dfs(bt.right);
        }
}

Here, the call to f is hard-coded, we can’t specify f as a parameter.

Alternative implementation

class BinTree {
	// ...

	void dfs() {
		if( left != null )
			left.dfs();
		f(this);
		if( right != null )
			right.dfs();
	}
}

dfs is a method.

Here, the call to f is hard-coded, we can’t specify f as a parameter.

import java.util.function.Consumer;
class BinTree<T> {
	// ...

	void dfs(Consumer<BinTree<T>> f) {
		if( left != null )
			left.dfs(f);
		f.accept(this);
		if( right != null )
			right.dfs(f);
	}
}

This works in java >= 8.

dfs is a method.

f is functional argument.

17. Create a Tree data structure

The structure must be recursive. A node may have zero or more children. A node has access to children nodes, but not to its parent.

import java.util.List;
import java.util.ArrayList;
class Tree<K,V> {
  K key;
  V deco;
  List<Tree<K,V>> children = new ArrayList<>();
}

Then you will want to add constructors, getters, setters.

19. Reverse a list

Reverse the order of the elements of list x.

This may reverse “in-place” and destroy the original ordering.

import java.util.List;
static <T> void reverse(List<T> x){
	int n = x.size();
	for(int i=0;i<n/2;i++){
		T tmp = x.get(i);
		x.set(i, x.get(n-i-1));
		x.set(n-i-1, tmp);
	}
}

This method works for lists of any element type T .

In case of an odd number of elements, the central element doesn’t need to be swapped.

Alternative implementation

import java.util.Collections;
Collections.reverse(x);
import java.util.Collections;
Collections.reverse(x);

20. Return two values

Implement a function search which looks for item x in a 2D matrix m.

Return indices i, j of the matching cell.

Think of the most idiomatic way in the language to return the two values at the same time.

static class Position{
	int i;
	int j;
}

Position search(int[][] m, int x){
	for(int i=0;i<m.length;i++)
		for(int j=0;j<m[i].length;j++)
			if(m[i][j] == x){
				Position pos= new Position();
				pos.i = i;
				pos.j = j;
				return pos;
			}
	return null;
}

A Java method returns 0 or 1 value only. So we have to create a custom class Position to hold the two values to return.

21. Swap values

Swap values of variables a and b

T tmp = a;
a = b;
b = tmp;

This assumes a and b are of type T.

T may be a class or a primitive type.

22. Convert string to integer

Extract integer value i from its string representation s (in radix 10)

int i = Integer.parseInt(s);

This will throw NumberFormatException if s does not contain a parsable integer

Alternative implementation

int i = new Integer(s).intValue();

This will throw NumberFormatException if s does not contain a parsable integer

23. Convert real number to string with 2 decimal places

Given real number x, create its string representation s with 2 decimal digits following the dot.

String s = String.format("%.2f", x);

24. Assign to string the japanese word ネコ

Declare a new string s and initialize it with the literal value “ネコ” (which means “cat” in japanese)

String s = "ネコ";

Literal strings with UTF-16 characters are legal in Java. Just be careful with your source file encoding, or use escaping.

25. Send a value to another thread

Share the string value “Alan” with an existing running process which will then display “Hello, Alan”

https://gist.github.com/f7c174c53efaba4d8575

I tried to put in in here, but it was just too long.

26. Create a 2-dimensional array

Declare and initialize a matrix x having m rows and n columns, containing real numbers.

double[][] x = new double[m][n];

Initial values are 0.0

m and n need not be known at compile time

27. Create a 3-dimensional array

Declare and initialize a 3D array x, having dimensions boundaries m, n, p, and containing real numbers.

double[][][] x = new double[m][n][p];

Initial values are 0.0

m, n, p need not be known at compile time

28. Sort by a property

Sort elements of array-like collection items in ascending order of x.p, where p is a field of the type Item of the objects in items.

import java.util.Arrays;
import java.util.Comparator;
Arrays.sort(items, new Comparator<Item>(){
	public int compare(Item a, Item b){
		return a.p - b.p;
	}
});

items is an array of type Item[].

Use an anonymous class which implements Comparator

Alternative implementation

import java.util.Collections;
import java.util.Comparator;
Collections.sort(items, new Comparator<Item>(){
	@Override
	public int compare(Item a, Item b){
		return a.p - b.p;
	}
});

items is a List.

Use an anonymous class which implements Comparator.

import java.util.Comparator;
items.stream().sorted(Comparator.comparing(x -> x.p))

29. Remove item from list, by its index

Remove i-th item from list items.

This will alter the original list or return a new list, depending on which is more idiomatic.

Note that in most languages, the smallest valid value for i is 0.

import java.util.List;
items.remove(i);

Original list is altered.

Be careful not to confuse remove(int) with remove(Object), in case you have a List (conversions can be tricky)

30. Parallelize execution of 1000 independent tasks

Launch the concurrent execution of procedure f with parameter i from 1 to 1000.

Tasks are independent and f(i) doesn’t return any value.

Tasks need not run all at the same time, so you may use a pool.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
final ExecutorService executor = Executors.newFixedThreadPool(NB_THREADS);
for (int i = 1; i <= 1000; i++) {
  executor.submit(() -> f(i));
}
executor.shutdown();

For a large number of tasks, use a thread pool.

31. Recursive factorial (simple)

Create recursive function f which returns the factorial of non-negative integer i, calculated from f(i-1)

int f(int i){
	if(i==0)
		return 1;
	else
		return i * f(i-1);
} 

Warnings : - type int quickly overflows - high number of recursive calls may cause a stack overflow - also, f is not tail-recursive

32. Integer exponentiation by squaring

Create function exp which calculates (fast) the value x power n.

x and n are non-negative integers.

int exp(int x, int n){
	if(n==0)
		return 1;
	if(n==1)
		return x;
	if(n%2==0)
		return exp(x*x, n/2);
	else
		return x * exp(x*x, (n-1)/2);
}

Warning : - type int quickly overflows

33. Atomically read and update variable

Assign variable x the new value f(x), making sure that no other thread may modify x between the read and the write.

synchronized(lock){
  x = f(x);
}

With this idiom, you have to manually ensure that any thread modifying x is guarded by the same lock object.

34. Create a Set of objects

Declare and initialize a Set x containing objects of type T.

import java.util.Set;
import java.util.HashSet;
Set<T> x = new HashSet<T>();

The type T must respect the equals() / hashcode() contract.

35. First-class function : compose

Implement a function compose (A -> C) with parameters f (A -> B) and g (B -> C), which returns composition function g°f

public <A,B,C> Function<A,C> compose(Function<A,B> f, Function<B,C> g){
   return x -> g.apply(f.apply(x));
}

Alternative implementation

import java.util.function.Function;
Function<Integer, Integer> addOne = i-> i + 1;
Function<Integer, String> toString = i-> i.toString();
Function<Integer, String> printIncremented = toString.compose(addOne);

36. First-class function : generic composition

Implement a function compose which returns composition function g°f for any functions f and g having exactly 1 parameter.

    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }

This is the implementation of the compose method in java.util.function.Function

37. Currying

Transform a function that takes multiple arguments into a function for which some of the arguments are preset.

import java.util.function.*;
IntBinaryOperator simpleAdd = (a, b) -> a + b;
IntFunction<IntUnaryOperator> curriedAdd = a -> b -> a + b;
System.out.println(simpleAdd.applyAsInt(4, 5));
System.out.println(curriedAdd.apply(4).applyAsInt(5));

38. Extract a substring

Find substring t consisting in characters i (included) to j (excluded) of string s.

(character indexes start at 0 unless specified otherwise)

String t = s.substring(i,j);

Throws IndexOutOfBoundsException if i is negative, or j is larger than the length of s, or i is larger than j.

39. Check if string contains a word

Set boolean ok to true if string word is contained in string s as a substring, or to false otherwise.

boolean ok = s.contains(word);

Function String.contains() exists since java 1.5

40. Graph with adjacency lists

Declare a Graph data structure in which each Vertex has a collection of its neighbouring vertices.

import java.util.List;
class Graph{
  List<Vertex> vertices;

  static class Vertex{
    int id;
    List<Vertex> neighbours;
  }
}

Of course, your implementation will also include constructors, edge methods, and graph traversal methods.

Alternative implementation

import java.util.Set;
class Graph{
  Set<Vertex> vertices;

  static class Vertex{
    int id;
    Set<Vertex> neighbours;
  }
}

Using Set containers is fine when order doesn’t matter.

Of course, your implementation will also include constructors, edge methods, and graph traversal methods.

41. Reverse a string

Create string t containing the same characters as string s, in reverse order.

Original string s must remain unaltered. Each character must be handled correctly regardless its number of bytes in memory.

String t = new StringBuilder(s).reverse().toString();

StringBuilder is available since Java 1.5

42. Continue outer loop

Print each item v of list a which in not contained in list b.

For this, write an outer loop to iterate on a and an inner loop to iterate on b.

mainloop: for(int v:a){
	for(int w:b){
		if(v==w)
			continue mainloop;
	}
	System.out.println(v);
}

mainloop is a label used to refer to the outer loop.

43. Break outer loop

Look for a negative value v in 2D integer matrix m. Print it and stop searching.

mainloop: for(int i=0;i<m.length;i++)
	for(int j=0;j<m[i].length;j++)
		if(m[i][j]<0){
			System.out.println(m[i][j]);
			break mainloop;
		}

mainloop is a label used to refer to the outer loop.

44. Insert element in list

Insert element x at position i in list s. Further elements must be shifted to the right.

import java.util.List;
s.add(i, x);

45. Pause execution for 5 seconds

Sleep for 5 seconds in current thread, before proceeding with next instructions.

Thread.sleep(5000);

Unit is millisecond

Alternative implementation

import java.util.concurrent.TimeUnit;
TimeUnit.SECONDS.sleep(5);

Java 7+

46. Extract beginning of string (prefix)

Create string t consisting of the 5 first characters of string s.

String t = s.substring(0,5);

s must not be null.

47. Extract string suffix

Create string t consisting in the 5 last characters of string s.

int n = s.length();
String t = s.substring(n-5,n);

s must not be null.

48. Multi-line string literal

Assign to variable s a string literal consisting in several lines of text

String s = "This is a very long string which needs " +
           "to wrap across multiple lines because " +
           "otherwise my code is unreadable.";

Credit goes to the JS equivalent—but I’m not sure how to provide a link.

49. Split a space-separated string

Build list chunks consisting in substrings of input string s, separated by one or more space characters.

String[] chunks = s.split("\\s+");

50. Make an infinite loop

Write a loop which has no end clause.

for(;;){
	// Do something
}

The three expressions in the for clause (initialization, termination, increment) are left empty.

Alternative implementation

while(true) {
	// Do something	
}

51. Check if map contains key

Determine whether map m contains an entry for key k

import java.util.Map;
m.containsKey(k)

52. Check if map contains value

Determine whether map m contains an entry with value v, for some key.

import java.util.Map;
m.containsValue(v)

53. Join a list of strings

Concatenate elements of string list x joined by the separator “, ” to create a single string y.

String y = String.join(", ", x);

This exists since Java 8.

54. Compute sum of integers

Calculate the sum s of integer list x.

int s = 0;
for (int i : x) {
  s += i;
}

55. Convert integer to string

Create the string representation s (in radix 10) of integer value i.

String s=((Integer)i).toString();

Alternative implementation

String s = Integer.parseInt(i);
String s = Integer.toString(i);

This is a static method, no need to create an Integer instance.

Alternative implementation

String s = String.valueOf(i);

This is a static method.

55. Convert integer to string

Create the string representation s (in radix 10) of integer value i.

String s = "" + i;

Probably not the most performant, but one of the shortest.

56. Launch 1000 parallel tasks and wait for completion

Fork-join : launch the concurrent execution of procedure f with parameter i from 1 to 1000.

Tasks are independent and f(i) doesn’t return any value.

Tasks need not run all at the same time, so you may use a pool.

Wait for the completion of the 1000 tasks and then print “Finished”.

import java.util.concurrent.*;
class Task implements Runnable {
	int i;
	Task(int i) {
		this.i = i;
	}
	@Override
	public void run() {
		f(i);
	}
}

ExecutorService executor = Executors.newFixedThreadPool(4);
for (int i = 1; i <= 1000; i++) {
	Task task = new Task(i);
	executor.submit(task);
}
executor.awaitTermination(10L, TimeUnit.MINUTES);
System.out.println("Finished");
```java
4 (in this example) is the size of the thread pool.

It will wait max 10mn.

### Alternative implementation
```java
import java.util.concurrent.*;
ExecutorService executor = Executors.newFixedThreadPool(4);
for (int i = 1; i <= 1000; i++) {
	Task task = new Task(i);
	executor.submit(() -> f(i));
}
executor.awaitTermination(10L, TimeUnit.MINUTES);
System.out.println("Finished");
```java
4 is the size of the thread pool.

It will wait max 10mn.

With lambdas, no wrapper is necessary.

## 57. Filter list
Create list y containing items from list x satisfying predicate p. Respect original ordering. Don't modify x in-place.
```java
var y = x.stream().filter(p).collect(Collectors.toList());

58. Extract file content to a string

Create string lines from the content of the file with filename f.

import java.nio.file.Files;
import java.nio.charset.StandardCharsets;
byte[] encoded = Files.readAllBytes(Paths.get(f));
String lines = new String(encoded, StandardCharsets.UTF_8);

You have to know and explicitly tell the charset used in the file.

59. Write to standard error stream

Print the message “x is negative” to standard error (stderr), with integer x value substitution (e.g. “-2 is negative”).

System.err.format("%d is negative\n",x);

60. Read command line argument

Assign to x the string value of the first command line parameter, after the program name.

String x = args[0];

This works only in method main(String[] args) .

61. Get current date

Assign to variable d the current date/time value, in the most standard type.

import java.time.Instant;
Instant d = Instant.now();

New in Java 8.

Use Date on java 7.

62. Find substring position

Set i to the position of string y inside string x, if exists.

int i = x.indexOf(y);

i will be -1 if the substring was not found in the string.

63. Replace fragment of a string

Assign to x2 the value of string x with all occurrences of y replaced by z.

Assume occurrences of y are not overlapping.

String x2 = x.replace(y, z);

For regex, use String.replaceAll instead.

64. Big integer : value 3 power 247

Assign to x the value 3^247

import java.math.BigInteger;
BigInteger x = new BigInteger("3", 10).pow(247);

This BigInteger constructor takes the value from a string, and you must specify the radix.

65. Format decimal number

From real value x in [0,1], create its percentage string representation s with one digit after decimal point. E.g. 0.15625 -> “15.6%”

import java.text.DecimalFormat;
String s = new DecimalFormat("0.0%").format(x);

This notation handles the multiplication by 100 for you.

66. Big integer exponentiation

Calculate the result z of x power n, where x is a big integer and n is a positive integer.

import java.math.BigInteger;
BigInteger z = x.pow(n);

This leaves x unchanged.

67. Binomial coefficient “n choose k”

Calculate binom(n, k) = n! / (k! * (n-k)!). Use an integer type able to handle huge numbers.

import java.math.BigInteger;
static BigInteger binom(int N, int K) {
    BigInteger ret = BigInteger.ONE;
    for (int k = 0; k < K; k++) {
        ret = ret.multiply(BigInteger.valueOf(N-k))
                 .divide(BigInteger.valueOf(k+1));
    }
    return ret;
}

68. Create a bitset

Create an object x to store n bits (n being potentially large).

import java.util.BitSet;
BitSet x = new BitSet(n);

The bitset will be able to grow if needed.

69. Seed random generator

Use seed s to initialize a random generator.

If s is constant, the generator output will be the same each time the program runs. If s is based on the current value of the system clock, the generator output will be different each time.

import java.util.Random;
Random r = new Random(s);

s is of type long.

70. Use clock as random generator seed

Get the current datetime and provide it as a seed to a random generator. The generator sequence will be different at each run.

import java.util.Random;
Random rand = new Random(System.currentTimeMillis());

71. Echo program implementation

Basic implementation of the Echo program: Print all arguments except the program name, separated by space, followed by newline.

The idiom demonstrates how to skip the first argument if necessary, concatenate arguments as strings, append newline and print it to stdout.

import static java.lang.String.join;
import static java.lang.System.out;
public class Echo {
    public static void main(final String... args) {
        out.println(join(" ", args));
    }
}

String.join() exists only since Java 8.

74. Compute GCD

Compute the greatest common divisor x of big integers a and b. Use an integer type able to handle huge numbers.

import java.math.BigInteger;
BigInteger x = a.gcd(b);

75. Compute LCM

Compute the least common multiple x of big integers a and b. Use an integer type able to handle huge numbers.

import java.math.BigInteger;
BigInteger a = new BigInteger("123456789");
BigInteger b = new BigInteger("987654321");
BigInteger x = a.multiply(b).divide(a.gcd(b));

76. Binary digits from an integer

Create the string s of integer x written in base 2.

E.g. 13 -> “1101”

String s = Integer.toBinaryString(x);

77. Complex number

Declare a complex x and initialize it with value (3i - 2). Then multiply it by i.

import org.apache.commons.math4.complex.Complex;
Complex x = new Complex(-2.0, 3.0);
x = x.multiply(Complex.I);

This uses the Apache Commons Math library.

78. “do while” loop

Execute a block once, then execute it again as long as boolean condition c is true.

do {
	someThing();
	someOtherThing();
} while(c);

The block code is not repeated in the source.

79. Convert integer to floating point number

Declare floating point number y and initialize it with the value of integer x .

float y = x;

80. Truncate floating point number to integer

Declare integer y and initialize it with the value of floating point number x . Ignore non-integer digits of x .

Make sure to truncate towards zero: a negative x must yield the closest greater integer (not lesser).

int y = (int)x;

81. Round floating point number to integer

Declare integer y and initialize it with the rounded value of floating point number x .

Ties (when the fractional part of x is exactly .5) must be rounded up (to positive infinity).

long y = Math.round(x);

Math.round() converts a float to an int, or a double to a long.

82. Count substring occurrences

Find how many times string s contains substring t.

Specify if overlapping occurrences are counted.

import org.apache.commons.lang3.StringUtils;
int count = StringUtils.countMatches(s, t);

This uses the Apache Commons Lang library.

83. Regex with character repetition

Declare regular expression r matching strings “http”, “htttp”, “httttp”, etc.

import java.util.regex.Pattern;
Pattern r = Pattern.compile("htt+p");

84. Count bits set in integer binary representation

Count number c of 1s in the integer i in base 2.

E.g. i=6 → c=2

int c = Integer.bitCount(i);

i has type int.

Warning: small negative numbers have a lot of bits set, because of the two’s complement.

Similar methods exist in classes Long and BigInteger.

85. Check if integer addition will overflow

Write boolean function addingWillOverflow which takes two integers x, y and return true if (x+y) overflows.

public boolean addingWillOverflow(int x, int y){
    boolean willOverFlow = false;
    if(x > 0 && y > 0){
        if(y > (Integer.MAX_VALUE - x)){
            willOverFlow = true;
        }
    }
    if(x < 0 && y < 0){
       if(y < (Integer.MIN_VALUE - x)){
           willOverFlow = true;
       }
    }
    return willOverFlow;
}

If both values are positive, make sure the difference between one and the MAX_VALUE is less than the other, otherwise they will overflow.

If both values are negative, make sure the difference between one and the MIN_VALUE is less than the other, otherwise they will underflow.

The case where one is negative and one is positive does not need to be checked as they will definitely not under or overflow in that scenario.

86. Check if integer multiplication will overflow

Write boolean function multiplyWillOverflow which takes two integers x, y and return true if (x*y) overflows.

static boolean multiplyWillOverflow(int x, int y) {
	return Integer.MAX_VALUE/x < y;
}

PROBLEM: this works only when x and y are positive.

87. Stop program

Exit immediatly.

If some extra cleanup work is executed by the program runtime (not by the OS itself), describe it.

System.exit(0);

This stops the whole JVM.

Status code 0 means “normal termination”.

88. Allocate 1M bytes

Create a new bytes buffer buf of size 1,000,000.

byte[] buf = new byte[1000000];

89. Handle invalid argument

You’ve detected that the integer value of argument x passed to the current function is invalid. Write the idiomatic way to abort the function execution and signal the problem.

throw new IllegalArgumentException("Invalid value for x:" + x);

IllegalArgumentException is a RuntimeException, thus it needn’t be declared in the function signature.

Other standard exceptions cover possible cases: NullPointerException, etc.

It is the caller’s responsibility to provide valid input, or catch the possible exceptions.

Alternative implementation

throw new IllegalArgumentException("The parameter _x is invalid because [...]")

93. Pass a runnable procedure as parameter

Implement procedure control which receives one parameter f, and runs f.

static void control(Runnable f) {
    f.run();
}

94. Print type of variable

Print the name of the type of x. Explain if it is a static type or dynamic type.

This may not make sense in all languages.

int a = 0;
String b = "str";
System.out.println(((Object)a).getClass().getName());
System.out.println(b.getClass().getName());

95. Get file size

Assign to variable x the length (number of bytes) of the local file at path.

import java.io.File;
long x = new File(path).length();

96. Check string prefix

Set boolean b to true if string s starts with prefix prefix, false otherwise.

boolean b = s.startsWith(prefix);

97. Check string suffix

Set boolean b to true if string s ends with string suffix, false otherwise.

boolean b = s.endsWith(suffix);

98. Epoch seconds to date object

Convert a timestamp ts (number of seconds in epoch-time) to a date with time d. E.g. 0 -> 1970-01-01 00:00:00

import java.util.Date;
Date date = new Date(numberOfSecondsSinceEpoch  * 1000);

numberOfSecondsSinceEpoch is our input. Since the date constructor expects a parameter that represents number of milliseconds since epoch, we need to multiply numberOfSecondsSinceEpoch with 1000 to convert it to milliseconds.

99. Format date YYYY-MM-DD

Assign to string x the value of fields (year, month, day) of date d, in format YYYY-MM-DD.

import java.text.SimpleDateFormat;
String x = new SimpleDateFormat("yyyy-MM-dd").format(d);

d has type java.util.Date.

A SimpleDateFormat instance may be reused, but is not thread-safe.

Alternative implementation

String x = String.format("%1$tY-%1$tm-%1$td", d)

Per documentation (see documentation URL), d may be:

long, Long, java.util.Date, java.util.Calendar, or java.time.temporal.TemporalAccessor (which then includes most java.time types)

100. Sort by a comparator

Sort elements of array-like collection items, using a comparator c.

import java.util.Arrays;
import java.util.Comparator;
Arrays.sort(items, c);

items is an array of type Item[].

c implements Comparator.

Alternative implementation

import java.util.Collections;
import java.util.Comparator;
Collections.sort(items, c);

items is a List.

c implements Comparator.

105. Current executable name

Assign to string s the name of the currently executing program (but not its full path).

String s = System.getProperty("sun.java.command");

This is the name of the archive or class executed with the jvm.

106. Get program working directory

Assign to string dir the path of the working directory.

(This is not necessarily the folder containing the executable itself)

String path = this.getClass().getClassLoader().getResource("").getPath();

110. Check if string is blank

Set boolean blank to true if string s is empty, or null, or contains only whitespace ; false otherwise.

import org.apache.commons.lang.StringUtils;
boolean blank = StringUtils.isBlank(s);

This uses external library Apache Commons Lang.

Alternative implementation

boolean blank = s.trim().isEmpty();

Use strip (Java 11) instead of trim for Unicode-awareness, or more simply use isBlank (Java 11)

112. Iterate over map entries, ordered by keys

Print each key k with its value x from an associative array mymap, in ascending order of k.

import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
SortedMap<K, V> mymap = new TreeMap<>();
...
for(Map.Entry<K, V> e: mymap.entrySet())
	System.out.println("Key=" + e.getKey() + ", Value=" + e.getValue());

When mymap implements SortedMap, sorted iteration is straightforward.

Alternative implementation

import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
List<K> keys = new ArrayList<>(mymap.keySet());
Collections.sort(keys);
for(K k: keys)
	System.out.println("Key=" + k + ", Value=" + mymap.get(k));

Extract keys, sort, iterate.

Keys have type K.

import java.util.Map;
import java.util.TreeMap;
var map = Map.of("a", 1, "d", 4, "c", 3, "b", 2);
new TreeMap<>(map).entrySet().forEach(System.out::println);

The normal iteration of a TreeMap will iterates its key in order.

Alternative implementation

import java.util.Map.Entry;
mymap.entrySet().stream().sorted(Entry.comparingByKey()).forEach(System.out::println);

115. Compare dates

Set boolean b to true if date d1 is strictly before date d2 ; false otherwise.

import java.util.Date;
boolean before = (d1.compareTo(d2) == -1);

d1, d2 are of type java.util.Date. variable before will contain true if d1 < d2, false otherwise

116. Remove occurrences of word from string

Remove all occurrences of string w from string s1, and store the result in s2.

String s2 = s1.replace(w, "");

This replaces the occurrences with an empty string.

117. Get list size

Set n to the number of elements of list x.

int n = x.size();

x implements java.util.List.

Alternative implementation

int n = x.length;

x is an array.

118. List to set

Create set y from list x.

x may contain duplicates. y is unordered and has no repeated values.

import java.util.HashSet;
import java.util.List;
Set<T> y = new HashSet<>(x);

T is the type of the elements.

119. Deduplicate list

Remove duplicates from list x.

Explain if original order is preserved.

import java.util.HashSet;
import java.util.List;
import java.util.Set;
Set<T> uniques = new HashSet<>(x);
x.clear();
x.addAll(uniques);

This uses the same List instance, emptied and then refilled.

Original ordering is not preserved.

Alternative implementation

import java.util.HashSet;
import java.util.ArrayList;
x = new ArrayList<T>(new HashSet<T>(x));

This creates a new ArrayList object.

Original ordering is not preserved.

import java.util.HashSet;
import java.util.Iterator;
final HashSet<T> seen = new HashSet<T>();
final Iterator<T> listIt = x.iterator();
while (listIt.hasNext()) {
  final T curr = listIt.next();
  if (seen.contains(curr)) {
    listIt.remove();
  } else {
    seen.add(curr);
  }
}

Preserves the order of the items.

Upon first occurrence, store item in seen; all future occurrences of the item are removed from the list via the iterator listIt, removing the last-returned item.

Requires extra memory for the hash-set.

Note that the runtime cost is O(n^2).

120. Read integer from stdin

Read an integer value from the standard input into variable n.

import java.util.Scanner;
Scanner in = new Scanner(System.in);
n = in.nextInt();

121. UDP listen and read

Listen UDP traffic on port p and read 1024 bytes into buffer b.

import java.net.DatagramSocket;
import java.net.DatagramPacket;
int len = 1024;
int p = 8888;
byte[] b = new byte[len];
try (DatagramSocket socket = new DatagramSocket(p)) {
  DatagramPacket packet = new DatagramPacket(b, len);
  socket.receive(packet);
}

122. Declare enumeration

Create an enumerated type Suit with 4 possible values SPADES, HEARTS, DIAMONDS, CLUBS.

enum Suit{
  SPADES,
  HEARTS,
  DIAMONDS,
  CLUBS;
}

123. Assert condition

Verify that predicate isConsistent returns true, otherwise report assertion violation.

Explain if the assertion is executed even in production environment or not.

assert isConsistent() : “State consistency violated”;

This throws an AssertionError when then condition is false.

By default, assertions are disabled at runtime.

Use java switch -enableassertions or -ea.

124. Binary search for a value in sorted array

Write function binarySearch which returns the index of an element having value x in sorted array a, or -1 if no such element.

import java.util.arrays;
static int binarySearch(final int[] arr, final int key) {
    final int index = Arrays.binarySearch(arr, key);
    return index < 0 ? - 1 : index;
}

126. Multiple return values

Write a function foo that returns a string and a boolean value.

static Object[] returnAnything() {
    return new Object[]{"a string", true};
}

public static void main (String[] args) {
    Object[] array = returnAnything();
    System.out.println(array[0]);
    System.out.println(array[1]);
}

128. Breadth-first traversing of a tree

Call a function f on every node of a tree, in breadth-first prefix order

import java.util.LinkedList;
import java.util.Queue;
import java.util.function.Consumer;
static void breadthFirstSearch(Node root, Consumer<Node> f) {
    Queue<Node> queue = new LinkedList<>();
    queue.offer(root);

    while(!queue.isEmpty()) {
        Node polled = queue.poll();
        f.accept(polled);
        polled.children.forEach(a -> queue.offer(a));
    }
}

131. Successive conditions

Execute f1 if condition c1 is true, or else f2 if condition c2 is true, or else f3 if condition c3 is true.

Don’t evaluate a condition when a previous condition was true.

if (c1) {
   f1();
} else if (c2) {
   f2();
} else if (c3) { 
   f3();
}

132. Measure duration of procedure execution

Run procedure f, and return the duration of the execution of f.

long clock(Runnable f) {
    long t0 = System.currentTimeMillis();
    f.run();
    long t1 = System.currentTimeMillis();
    return t1 - t0;
}

Parameter f is actually a Runnable object, having a run() method.

The result is in milliseconds.

133. Case-insensitive string contains

Set boolean ok to true if string word is contained in string s as a substring, even if the case doesn’t match, or to false otherwise.

ok = s.toLowerCase().contains(word.toLowerCase());

134. Create a new list

Declare and initialize a new list items, containing 3 elements a, b, c.

import java.util.List;
import java.util.ArrayList;
List<T> items = new ArrayList<>();
items.add(a);
items.add(b);
items.add(c);

T is the type of a, b, c.

Alternative implementation

import java.util.List;
import java.util.Arrays;
List<T> items = Arrays.asList(a, b, c);

T is the type of a, b, c.

135. Remove item from list, by its value

Remove at most 1 item from list items, having value x.

This will alter the original list or return a new list, depending on which is more idiomatic. If there are several occurrences of x in items, remove only one of them.

Java.utils.List
items.stream().findFirst().filter(item -> "x".equals(item)).ifPresent(removeIndex -> items.remove(removeIndex));

136. Remove all occurrences of a value from a list

Remove all occurrences of value x from list items.

This will alter the original list or return a new list, depending on which is more idiomatic.

import java.util.Collections;
items.removeAll(Collections.singleton(x));
items has type java.util.List.
items is altered by removeAll().

137. Check if string contains only digits

Set boolean b to true if string s contains only characters in range ‘0’..‘9’, false otherwise.

boolean b = s.matches("[0-9]*");

This uses a regular expression.

140. Delete map entry

Delete from map m the entry having key k.

Explain what happens if k is not an existing key in m.

map.remove(k);

Remove the entry for the key k from the map.

Returns null if the map does not have an entry for k

141. Iterate in sequence over two lists

Iterate in sequence over the elements of the list items1 then items2. For each iteration print the element.

items1.forEach(System.out::println);
items2.forEach(System.out::println);

Alternative implementation

for (String item : items1) {
	System.out.println(item);
}
for (String item : items2) {
	System.out.println(item);
}
import java.util.stream.Stream;
Stream.concat(
	items1.stream(), 
	items2.stream()
).forEach(System.out::println);

142. Hexadecimal digits of an integer

Assign to string s the hexadecimal representation (base 16) of integer x.

E.g. 999 -> “3e7”

String s = Integer.toHexString(x);

143. Iterate alternatively over two lists

Iterate alternatively over the elements of the list items1 and items2. For each iteration, print the element.

Explain what happens if items1 and items2 have different size.

import java.util.Iterator;
Iterator<String> iter1 = items1.iterator();
Iterator<String> iter2 = items2.iterator();
while (iter1.hasNext() || iter2.hasNext()) {
	if (iter1.hasNext()) {
		System.out.println(iter1.next());
	}
	if (iter2.hasNext()) {
		System.out.println(iter2.next());
	}
}

Alternative implementation

import java.util.stream.IntStream;
import java.util.stream.Stream;
IntStream.range(0, Math.max(items1.size(), items2.size()))
	.boxed()
	.flatMap(idx -> Stream.of(
		items1.size() > idx ? items1.get(idx) : null,
		items2.size() > idx ? items2.get(idx) : null
	))
	.filter(Objects::nonNull)
	.forEach(System.out::println);

Get a stream of the list indices.

For each index, map to the elements from the lists at that index

Filter out null values which occur when the index is after the end of the list

Print the result

144. Check if file exists

Set boolean b to true if file at path fp exists on filesystem; false otherwise.

Beware that you should never do this and then in the next instruction assume the result is still valid, this is a race condition on any multitasking OS.

import java.io.File;
boolean b = new File(fb).exists();

145. Print log line with datetime

Print message msg, prepended by current date and time.

Explain what behavior is idiomatic: to stdout or stderr, and what the date format is.

import java.util.logging.Logger;
Logger LOGGER = Logger.getLogger(MyClass.class.getName());

LOGGER.info(msg);

LOGGER should be declared private and final, at the beginning of the class.

146. Convert string to floating point number

Extract floating point value f from its string representation s

String floatString = "14.5";
float x = Float.parseFloat(floatString);
double y = Double.parseFloat(floatString);

Will throw NullPointerException if floatString is null or NumberFormatException if the string is not actually a float.

147. Remove all non-ASCII characters

Create string t from string s, keeping only ASCII characters

String t = s.replaceAll("[^\\x00-\\x7F]", "");

149. Rescue the princess

As an exception, this content is not under license CC BY-SA 3.0 like the rest of this website.

150. Remove trailing slash

Remove last character from string p, if this character is a slash /.

if (p.endsWith("/")) {
    p = p.substring(0, p.length() - 1);
}

Alternative implementation

p = p.replaceAll("/$", "");

$ here means “end of string”

152. Turn a character into a string

Create string s containing only the character c.

String s = String.valueOf(c);

Alternative implementation

String s = Character.toString(c);
String s = c + "";

This “lazy way” is quite common, but slow at runtime.

Alternative implementation

String s = = new Character(c).toString();

153. Concatenate string with integer

Create string t as the concatenation of string s and integer i.

String t = s + i;

Operator + works just fine.

154. Halfway between two hex color codes

Find color c, the average between colors c1, c2.

c, c1, c2 are strings of hex color codes: 7 chars, beginning with a number sign # .

Assume linear computations, ignore gamma corrections.

String r1 = c1.substring(1,3);
String g1 = c1.substring(3,5);
String b1 = c1.substring(5,7);

String r2 = c2.substring(1,3);
String g2 = c2.substring(3,5);
String b2 = c2.substring(5,7);

String r = String.format("%02X", (Integer.parseInt(r1, 16)+Integer.parseInt(r2, 16))/2 );
String g = String.format("%02X", (Integer.parseInt(g1, 16)+Integer.parseInt(g2, 16))/2 );
String b = String.format("%02X", (Integer.parseInt(b1, 16)+Integer.parseInt(b2, 16))/2 );

String c = "#" + r + g + b;

Alternative implementation

StringBuilder sb = new StringBuilder("#");
for(int i=0;i<3;i++) {
  String sub1 = c1.substring(1+2*i,3+2*i);
  String sub2 = c2.substring(1+2*i,3+2*i);
  int v1 = Integer.parseInt(sub1, 16);
  int v2 = Integer.parseInt(sub2, 16);
  int v = (v1 + v2)/2;
  String sub = String.format("%02X", v);
  sb.append(sub);
}
String c = sb.toString();

Loops over each component r, g, b.

155. Delete file

Delete from filesystem the file having path filepath.

import java.io.File;
new File(filepath).delete();

156. Format integer with zero-padding

Assign to string s the value of integer i in 3 decimal digits. Pad with zeros if i < 100. Keep all digits if i ≥ 1000.

String s = String.format("%03d", i);

157. Declare constant string

Initialize a constant planet with string value “Earth”.

static final String planet = "Earth";

It is common and idiomatic (but not mandatory) to declare the constant as static, as a class member.

160. Detect if 32-bit or 64-bit architecture

Execute f32() if platform is 32-bit, or f64() if platform is 64-bit.

This can be either a compile-time condition (depending on target) or a runtime detection.

switch(System.getProperty("sun.arch.data.model")) {
  case "64": 
    f64(); 
    break;
  case "32":
    f32();
    break;
}

161. Multiply all the elements of a list

Multiply all the elements of the list elements by a constant c

import java.util.stream.Collectors;
elements.stream().map(e -> e*c).collect(Collectors.toList())
elements is of type List<Integer>, or something that can be multiplied.

stream turns it into a stream.

map does the multiplication

collect turns it back into a List.

Unlike other solutions here, this does not modify the original list.

165. Last element of list

Assign to variable x the last element of list items.

int x = items[items.length - 1];

166. Concatenate two lists

Create list ab containing all the elements of list a, followed by all elements of list b.

var ab = new ArrayList<>(a);
ab.addAll(b);

The first line creates a new array list and puts all the elements from a inside it. The second line adds the b elements.

167. Trim prefix

Create string t consisting of string s with its prefix p removed (if s starts with p).

String t = s.replaceFirst("^" + p, "");

This works if p doesn’t contain any regexp control characters

169. String length

Assign to integer n the number of characters of string s.

This can be different from the number of bytes of s.

int n = s.length();

This works only if s != null.

If s == null, this throws a NullPointerException.

170. Get map size

Set n to the number of elements stored in mymap.

This is not always equal to the map capacity.

int n = mymap.size();

171. Add an element at the end of a list

Append element x to the list s.

import java.util.List;
import java.util.ArrayList;
List<String> stringList = new ArrayList<>();
stringList.add("hello")

173. Format a number with grouped thousands

Number will be formatted with a comma separator between every group of thousands.

String.format("%,d", 1000000);

179. Get center of a rectangle

Return the center c of the rectangle with co?rdinates(x1,y1,x2,y2)

double[] c = {(x1+x2)/2,(y1+y2)/2};

c is double array that can be accessed using index 0 for x and 1 for y.

e.g. center[0]

180. List files in directory

Create list x containing the contents of directory d.

x may contain files and subfolders.

No recursive subfolder listing.

import java.io.File;
final File directory = new File(dirPath);
final File[] files = file.listFiles();

182. Quine program

Output the source of the program.

public class Quine
{
  public static void main(String[] args)
  {
    char q = 34;      // Quotation mark character
    String[] l = {    // Array of source code
    "public class Quine",
    "{",
    "  public static void main(String[] args)",
    "  {",
    "    char q = 34;      // Quotation mark character",
    "    String[] l = {    // Array of source code",
    "    ",
    "    };",
    "    for(int i = 0; i < 6; i++)           // Print opening code",
    "        System.out.println(l[i]);
``

## 184. Tomorrow
Assign to variable t a string representing the day, month and year of the day after the current date.
```java
import java.time.LocalDate;
LocalDate t = LocalDate.now().plusDays(1);

Java 8

185. Execute function in 30 seconds

Schedule the execution of f(42) in 30 seconds.

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.schedule(() -> _f(42), delayInSeconds, TimeUnit.SECONDS);

186. Exit program cleanly

Exit a program cleanly indicating no error to OS

System.exit(0);

187. Disjoint Set

Disjoint Sets hold elements that are partitioned into a number of disjoint (non-overlapping) sets.

public class DisjointSetElement {
  private DisjointSetElement representative = this;

  public DisjointSetElement getRepresentative() {
    if (representative != this) {
      representative = representative.getRepresentative();
    }
    return representative;
  }

  public void union(DisjointSetElement other) {
    other.getRepresentative().representative = getRepresentative();
  }
}

The class is usually subclassed with each element holding information about that specific element, and information about the aggregated set. The aggregated information is only used on the representative node

197. Get a list of lines from a file

Retrieve the contents of file at path into a list of strings lines, in which each element is a line of the file.

import java.io.File;
import java.nio.file.Files;
List<String> lines = Files.readAllLines(new File(path).toPath());

202. Sum of squares

Calculate the sum of squares s of data, an array of floating point values.

import java.util.Arrays;
Arrays.stream(data).map(i -> i * i).sum()

226. Delete last element from list

Remove the last element from list items.

import java.util.List;
items.remove(items.size() - 1);

source:Programming-Idioms.org

Tags:Java
Source:https://www.programming-idioms.org/cheatsheet/Java