logo

Java Cheatsheet

Array / List

Initialization:

// Create empty:
List<Integer> v = new ArrayList<>();

// Array
String[] arr = new String[]{"A", "B", "C"};

// List
List<Integer> list = new ArrayList<>(Arrays.asList(5, 4, 3, 2, 1));

// Init Stream
Stream<Integer> intStream = Stream.of(1,2,3,4);

// Copy from existing:
List<Integer> copy = new ArrayList<>(origin)

// Add
list.add()

// Join As String
String joined = String.join(",", Arrays.asList("a", "b", "c"));
String joined = Arrays.asList("a", "b", "c").stream().collect(Collectors.joining(","));
// Manipulate before joining, e.g. to Uppercase
String joined = Arrays.asList("a", "b", "c")
    .stream()
    .map(String::toUpperCase)
    .collect(Collectors.joining(","));
// Another example:
List<BigDecimal> buffer = ...
String s = buffer.stream()
              .map(x -> x.toString())
              .collect(Collectors.joining(","));

Array to Stream

Arrays.stream(array);

String to IntStream

IntStream is = "abc".chars();

Array to Immutable List

private static final Thing[] PRIVATE_VALUES = { ... };
public static final List<Thing> VALUES =
    Collections.unmodifiableList(Arrays.asList(PRIVATE_VALUES));

Arrays.asList does not return ArrayList, so does not support addAll() or add(), will throw UnsupportedOperationException

Convert to string array

String[] y = x.toArray(new String[0]);

Primitive Array To List

Use boxed()

int[] nums = new int[]{1,2,3};
List<Integer> list = Arrays.stream(nums).boxed().collect(Collectors.toList());

Array To List

Integer[] nums = new Integer[]{1,2,3};
List<Integer> list = Arrays.stream(nums).collect(Collectors.toList());

Create ArrayList From Array

ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(1, 2, 3, 4));

Max / Min

int[] a = new int[]{1,2,3};
int min = Arrays.stream(a).min().getAsInt();

Map

// create
Map<Character, Integer> m = new HashMap<>();

// set value
m.put('a', 1);

// get value
m.get('a');

// get keys
Map<Integer, String> map = new HashMap<>();

List<Integer> result = map.entrySet().stream()
    .map(x -> x.getKey())
    .collect(Collectors.toList());

Set

Init EnumSet

EnumSet.of(Style.BOLD, Style.ITALIC);

Intersection: Use the retainAll() method of Set:

Set<String> s1;
Set<String> s2;
s1.retainAll(s2); // s1 now contains only elements in both sets

Remove Duplicates

Collection<Type> noDups = new HashSet<Type>(c);
Collection<Type> noDups = new LinkedHashSet<Type>(c);

Set<String> s = new HashSet<String>();
for (String a : args)
    if (!s.add(a))
        System.out.println("Duplicate detected: " + a);

System.out.println(s.size() + " distinct words: " + s);

Network

In java.net, Java programs can use TCP or UDP to communicate over the Internet. The URL, URLConnection, Socket, and ServerSocket classes all use TCP to communicate over the network. The DatagramPacket, DatagramSocket, and MulticastSocket classes are for use with UDP.

java.net.URL vs java.net.URI: java.net.URL#equals is blocking:

Two hosts are considered equivalent if both host names can be resolved into the same IP addresses; else if either host name can't be resolved, the host names must be equal without regard to case; or both host names equal to null. Since hosts comparison requires name resolution, this operation is a blocking operation.

Read Web Pages

final URL url = new URL("http://ichart.finance.yahoo.com/table.csv?s=" + ticker);
final BufferedReader reader = new BufferedReader( new InputStreamReader(url.openStream()));