Cheat Sheets For Java Developers
Cheat Sheets For Java Developers
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
. 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
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 **
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
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
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
. 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.