You are on page 1of 7

MUST-HAVE CHEAT SHEETS

FOR JAVA DEVELOPERS


CONCISE, HELPFUL, BEAUTIFUL, PRINTABLE

h eat ts!
C ee
Sh TU
RN
AR
OU
ND

RO
ZE
by

by Z E R O T U R N A R O U N D
Java 8 Streams Cheat Sheet

Definitions Stream examples Parallel streams


Get the unique surnames in uppercase of the first 15 book Parallel streams use the common ForkJoinPool for threading.
A stream is a pipeline of functions authors that are 50 years old or over. library.parallelStream()...
that can be evaluated.
library.stream()
.map(book -> book.getAuthor()) or intermediate operation:
Streams can transform data. .filter(author -> author.getAge() >= 50) IntStream.range(1, 10).parallel()...
.distinct()
A stream is not a data structure. .limit(15)
.map(Author::getSurname)
.map(String::toUpperCase)
Useful operations
Streams cannot mutate data. .collect(toList()); Grouping:
library.stream().collect(
Compute the sum of ages of all female authors younger than 25. groupingBy(Book::getGenre));
library.stream()
Intermediate operations .map(Book::getAuthor) Stream ranges:

. Always return streams. . Lazily executed. .filter(a -> a.getGender() == Gender.FEMALE) IntStream.range(0, 20)...
.map(Author::getAge)
.filter(age -> age < 25) Infinite streams:
.reduce(0, Integer::sum): IntStream.iterate(0, e -> e + 1)...
Common examples include:
Max/Min:
Preserves Preserves Preserves IntStream.range(1, 10).max();
Function
count type order Terminal operations
. Return concrete types or produce a side effect. FlatMap:

. Eagerly executed.
twitterList.stream()
map .map(member -> member.getFollowers())
.flatMap(followers -> followers.stream())
.collect(toList());
Common examples include:
filter
Function Output When to use Pitfalls
distinct Don’t update shared mutable
reduce concrete type to cumulate elements variables i.e.
List<Book> myList =
new ArrayList<>();
sorted library.stream().forEach
collect list, map or set to group elements
(e -> myList.add(e));
to perform a side effect
peek forEach side effect Avoid blocking operations
on elements
when using parallel streams.
BROUGHT TO YOU BY
Java Collections Cheat Sheet

What can your collection do for you?


Notable Java collections
libraries Your data Operations on your collections

Collection class Thread-safe alternative Duplicate Order of iteration Performant Random access
Individual Key-value Primitive
element ‘contains’
elements pairs support
support FIFO Sorted LIFO check By key By value By index
Fastutil
HashMap ConcurrentHashMap
http://fastutil.di.unimi.it/
Fast & compact type-specific collections for Java Maps.synchronizedBiMap
HashBiMap (Guava)
(new HashBiMap())
Great default choice for collections of primitive
ArrayListMultimap Maps.synchronizedMultiMap
types, like int or long. Also handles big
(Guava) (new ArrayListMultimap())
collections with more than 231 elements well.
Collections.synchronizedMap
LinkedHashMap
(new LinkedHashMap())

TreeMap ConcurrentSkipListMap * *
Guava
https://github.com/google/guava Int2IntMap (Fastutil)
Google Core Libraries for Java 6+
ArrayList CopyOnWriteArrayList
Perhaps the default collection library for Java
projects. Contains a magnitude of convenient Collections.newSetFromMap
HashSet
(new ConcurrentHashMap<>())
methods for creating collection, like fluent
builders, as well as advanced collection types. IntArrayList (Fastutil)

PriorityQueue PriorityBlockingQueue **

Eclipse Collections ArrayDeque ArrayBlockingQueue ** **


https://www.eclipse.org/collections/
* O(log(n)) complexity, while all others are O(1) - constant time ** when using Queue interface methods: offer() / poll()
Features you want with the collections you need
Previously known as gs-collections, this library
includes almost any collection you might How fast are your collections?
need: primitive type collections, multimaps,
bidirectional maps and so on. Random access Search /
Collection class Insert Remember, not all operations are equally fast. Here’s a reminder
by index / key Contains
of how to treat the Big-O complexity notation:

ArrayList O(1) O(n) O(n) O(1) - constant time, really fast, doesn’t depend on the
JCTools size of your collection
https://github.com/JCTools/JCTools HashSet O(1) O(1) O(1)
Java Concurrency Tools for the JVM. O(log(n)) - pretty fast, your collection size has to be
If you work on high throughput concurrent extreme to notice a performance impact
HashMap O(1) O(1) O(1)
applications and need a way to increase your
O(n) - linear to your collection size: the larger your
performance, check out JCTools.
TreeMap O(log(n)) O(log(n)) O(log(n)) collection is, the slower your operations will be BROUGHT TO YOU BY
Git Cheat Sheet

Create a Repository Working with Branches Make a change Synchronize


From scratch -- Create a new local List all local branches Stages the file, ready for commit Get the latest changes from origin
repository $ git branch $ git add [file] (no merge)
$ git init [project name] $ git fetch
List all branches, local and remote Stage all changed files, ready for commit
Download from an existing repository $ git branch -av $ git add . Fetch the latest changes from origin
$ git clone my_url and merge
Switch to a branch, my_branch, Commit all staged files to versioned history $ git pull
and update working directory $ git commit -m “commit message”
Observe your Repository $ git checkout my_branch Fetch the latest changes from origin
List new or modified files not yet Commit all your tracked files to and rebase
committed Create a new branch called new_branch versioned history $ git pull --rebase
$ git status $ git branch new_branch $ git commit -am “commit message”
Push local changes to the origin
Show the changes to files not yet staged Delete the branch called my_branch Unstages file, keeping the file changes $ git push
$ git diff $ git branch -d my_branch $ git reset [file]

Show the changes to staged files Merge branch_a into branch_b


Finally!
Revert everything to the last commit
$ git diff --cached $ git checkout branch_b When in doubt, use git help
$ git reset --hard
$ git merge branch_a $ git command --help
Show all staged and unstaged
file changes
Tag the current commit Or visit https://training.github.com/
$ git diff HEAD
$ git tag my_tag for official GitHub training.
Show the changes between two
commit ids
$ git diff commit1 commit2

List the change dates and authors


for a file
$ git blame [file]

Show the file changes for a commit


id and/or file
$ git show [commit]:[file]

Show full change history


$ git log

Show change history for file/directory


including diffs
$ git log -p [file/directory] BROUGHT TO YOU BY
cheat sheet

Getting started with Maven Useful command line options Essential plugins
Create Java project -DskipTests=true compiles the tests, but skips Help plugin — used to get relative information about a
mvn archetype:generate running them project or the system.
-DgroupId=org.yourcompany.project mvn help:describe describes the attributes of a plugin
-DartifactId=application -Dmaven.test.skip=true skips compiling the tests mvn help:effective-pom displays the effective POM
and does not run them
as an XML for the current build, with the active profiles
Create web project -T - number of threads: factored in.
mvn archetype:generate -T 4 is a decent default
-DgroupId=org.yourcompany.project -T 2C - 2 threads per CPU Dependency plugin — provides the capability to
-DartifactId=application manipulate artifacts.
-DarchetypeArtifactId=maven-archetype-webapp -rf, --resume-from resume build from the mvn dependency:analyze analyzes the dependencies
specified project
of this project
Create archetype from existing project -pl, --projects makes Maven build only specified mvn dependency:tree prints a tree of dependencies
mvn archetype:create-from-project modules and not the whole project
Compiler plugin — compiles your java code.
Main phases -am, --also-make makes Maven figure out what Set language level with the following configuration:
modules out target depends on and build them too <plugin>
clean — delete target directory
validate — validate, if the project is correct <groupId>org.apache.maven.plugins</groupId>
-o, --offline work offline
compile — compile source code, classes stored <artifactId>maven-compiler-plugin</
in target/classes -X, --debug enable debug output artifactId>
test — run tests <version>3.6.1</version>
package — take the compiled code and package it in its -P, --activate-profiles comma-delimited list <configuration>
distributable format, e.g. JAR, WAR of profiles to activate <source>1.8</source>
verify — run any checks to verify the package is valid <target>1.8</target>
-U, --update-snapshots forces a check for updated </configuration>
and meets quality criteria
dependencies on remote repositories
install — install the package into the local repository </plugin>
deploy — copies the final package to the remote repository -ff, --fail-fast stop at first failure
Version plugin — used when you want to manage
the versions of artifacts in a project's POM.

Plugins
compile maven-compiler-plugin compiler:compile Wrapper plugin — an easy way to ensure
Central Dependencies a user of your Maven build has everything
that is necessary.
test

Local Repository Spring Boot plugin — compiles your


~/.m2/settings.xml package maven-jar-plugin jar:jar Spring Boot app, build an executable fat jar.

Exec — amazing general purpose plugin,


BROUGHT TO YOU BY
SQL cheat sheet

Basic Queries The Joy of JOINs


-- filter your columns
SELECT col1, col2, col3, ... FROM table1
-- filter the rows

A B A B
WHERE col4 = 1 AND col5 = 2
-- aggregate the data
GROUP by …
-- limit aggregated data
HAVING count(*) > 1
-- order of the results
ORDER BY col2 LEFT OUTER JOIN - all rows from table A, INNER JOIN - fetch the results that RIGHT OUTER JOIN - all rows from table B,
even if they do not exist in table B exist in both tables even if they do not exist in table A
Useful keywords for SELECTS:
DISTINCT - return unique results
BETWEEN a AND b - limit the range, the values can be Updates on JOINed Queries Useful Utility Functions
numbers, text, or dates You can use JOINs in your UPDATEs -- convert strings to dates:
LIKE - pattern search within the column text UPDATE t1 SET a = 1 TO_DATE (Oracle, PostgreSQL), STR_TO_DATE (MySQL)
IN (a, b, c) - check if the value is contained among given. FROM table1 t1 JOIN table2 t2 ON t1.id = t2.t1_id -- return the first non-NULL argument:
WHERE t1.col1 = 0 AND t2.col2 IS NULL; COALESCE (col1, col2, “default value”)
-- return current time:
Data Modification NB! Use database specific syntax, it might be faster! CURRENT_TIMESTAMP
-- update specific data with the WHERE clause -- compute set operations on two result sets
UPDATE table1 SET col1 = 1 WHERE col2 = 2 Semi JOINs SELECT col1, col2 FROM table1
-- insert values manually UNION / EXCEPT / INTERSECT
You can use subqueries instead of JOINs: SELECT col3, col4 FROM table2;
INSERT INTO table1 (ID, FIRST_NAME, LAST_NAME)
VALUES (1, ‘Rebel’, ‘Labs’); SELECT col1, col2 FROM table1 WHERE id IN
-- or by using the results of a query (SELECT t1_id FROM table2 WHERE date > Union - returns data from both queries
INSERT INTO table1 (ID, FIRST_NAME, LAST_NAME) CURRENT_TIMESTAMP) Except - rows from the first query that are not present
SELECT id, last_name, first_name FROM table2 in the second query
Intersect - rows that are returned from both queries
Indexes
Views If you query by a column, index it!
A VIEW is a virtual table, which is a result of a query. CREATE INDEX index1 ON table1 (col1) Reporting
They can be used to create virtual tables of complex queries. Use aggregation functions
Don’t forget:
CREATE VIEW view1 AS COUNT - return the number of rows
SELECT col1, col2 Avoid overlapping indexes SUM - cumulate the values
FROM table1 Avoid indexing on too many columns AVG - return the average for the group
BROUGHT TO YOU BY
WHERE … Indexes can speed up DELETE and UPDATE operations MIN / MAX - smallest / largest value
Regex cheat sheet

Character classes Useful Java classes & methods Quantifiers


[abc] matches a or b, or c. PATTERN
[^abc] negation, matches everything except a, b, or c. A pattern is a compiler representation of a regular expression. Greedy Reluctant Possessive Description
[a-c] range, matches a or b, or c.
Pattern compile(String regex)
[a-c[f-h]] union, matches a, b, c, f, g, h. X? X?? X?+ X, once or not at all.
Compiles the given regular expression into a pattern.
[a-c&&[b-c]] intersection, matches b or c.
[a-c&&[^b-c]] subtraction, matches a. X* X*? X*+ X, zero or more times.
Pattern compile(String regex, int flags)
Compiles the given regular expression into a pattern
Predefined character classes with the given flags. X+ X+? X++ X, one or more times.

. Any character. boolean matches(String regex) X{n} X{n}? X{n}+ X, exactly n times.
\d A digit: [0-9] Tells whether or not this string matches the given
\D A non-digit: [^0-9] regular expression.
\s A whitespace character: [ \t\n\x0B\f\r] X{n,} X{n,}? X{n,}+ X, at least n times.
\S A non-whitespace character: [^\s] String[] split(CharSequence input)
\w A word character: [a-zA-Z_0-9] Splits the given input sequence around matches of X, at least n but
X{n,m} X{n,m}? X{n,m}+
\W A non-word character: [^\w] this pattern. not more than m times.

String quote(String s) Greedy - matches the longest matching group.


Boundary matches Returns a literal pattern String for the specified String. Reluctant - matches the shortest group.
^ The beginning of a line. Possessive - longest match or bust (no backoff).
$ The end of a line. Predicate<String> asPredicate()
\b A word boundary. Creates a predicate which can be used to match a string.
\B A non-word boundary. Groups & backreferences
\A The beginning of the input. MATCHER
\G The end of the previous match. An engine that performs match operations on a character A group is a captured subsequence of characters which may
\Z The end of the input but for the final terminator, if any. sequence by interpreting a Pattern. be used later in the expression with a backreference.
\z The end of the input. boolean matches()
(...) - defines a group.
Attempts to match the entire region against the pattern.
\N - refers to a matched group.
Pattern flags boolean find()
(\d\d) - a group of two digits.
Pattern.CASE_INSENSITIVE - enables case-insensitive Attempts to find the next subsequence of the input
(\d\d)/\1- two digits repeated twice.
matching. sequence that matches the pattern.
\1 - refers to the matched group.
Pattern.COMMENTS - whitespace and comments starting
with # are ignored until the end of a line. int start()
Pattern.MULTILINE - one expression can match
multiple lines.
Returns the start index of the previous match.
Logical operations
Pattern.UNIX_LINES - only the '\n' line terminator int end() XY X then Y. BROUGHT TO YOU BY
is recognized in the behavior of ., ^, and $. Returns the offset after the last character matched. X|Y X or Y.

You might also like