\documentclass[10pt,a4paper]{article} % Packages \usepackage{fancyhdr} % For header and footer \usepackage{multicol} % Allows multicols in tables \usepackage{tabularx} % Intelligent column widths \usepackage{tabulary} % Used in header and footer \usepackage{hhline} % Border under tables \usepackage{graphicx} % For images \usepackage{xcolor} % For hex colours %\usepackage[utf8x]{inputenc} % For unicode character support \usepackage[T1]{fontenc} % Without this we get weird character replacements \usepackage{colortbl} % For coloured tables \usepackage{setspace} % For line height \usepackage{lastpage} % Needed for total page number \usepackage{seqsplit} % Splits long words. %\usepackage{opensans} % Can't make this work so far. Shame. Would be lovely. \usepackage[normalem]{ulem} % For underlining links % Most of the following are not required for the majority % of cheat sheets but are needed for some symbol support. \usepackage{amsmath} % Symbols \usepackage{MnSymbol} % Symbols \usepackage{wasysym} % Symbols %\usepackage[english,german,french,spanish,italian]{babel} % Languages % Document Info \author{nixik09} \pdfinfo{ /Title (java-refresher.pdf) /Creator (Cheatography) /Author (nixik09) /Subject (Java refresher Cheat Sheet) } % Lengths and widths \addtolength{\textwidth}{6cm} \addtolength{\textheight}{-1cm} \addtolength{\hoffset}{-3cm} \addtolength{\voffset}{-2cm} \setlength{\tabcolsep}{0.2cm} % Space between columns \setlength{\headsep}{-12pt} % Reduce space between header and content \setlength{\headheight}{85pt} % If less, LaTeX automatically increases it \renewcommand{\footrulewidth}{0pt} % Remove footer line \renewcommand{\headrulewidth}{0pt} % Remove header line \renewcommand{\seqinsert}{\ifmmode\allowbreak\else\-\fi} % Hyphens in seqsplit % This two commands together give roughly % the right line height in the tables \renewcommand{\arraystretch}{1.3} \onehalfspacing % Commands \newcommand{\SetRowColor}[1]{\noalign{\gdef\RowColorName{#1}}\rowcolor{\RowColorName}} % Shortcut for row colour \newcommand{\mymulticolumn}[3]{\multicolumn{#1}{>{\columncolor{\RowColorName}}#2}{#3}} % For coloured multi-cols \newcolumntype{x}[1]{>{\raggedright}p{#1}} % New column types for ragged-right paragraph columns \newcommand{\tn}{\tabularnewline} % Required as custom column type in use % Font and Colours \definecolor{HeadBackground}{HTML}{333333} \definecolor{FootBackground}{HTML}{666666} \definecolor{TextColor}{HTML}{333333} \definecolor{DarkBackground}{HTML}{2FD4C9} \definecolor{LightBackground}{HTML}{F2FCFB} \renewcommand{\familydefault}{\sfdefault} \color{TextColor} % Header and Footer \pagestyle{fancy} \fancyhead{} % Set header to blank \fancyfoot{} % Set footer to blank \fancyhead[L]{ \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{C} \SetRowColor{DarkBackground} \vspace{-7pt} {\parbox{\dimexpr\textwidth-2\fboxsep\relax}{\noindent \hspace*{-6pt}\includegraphics[width=5.8cm]{/web/www.cheatography.com/public/images/cheatography_logo.pdf}} } \end{tabulary} \columnbreak \begin{tabulary}{11cm}{L} \vspace{-2pt}\large{\bf{\textcolor{DarkBackground}{\textrm{Java refresher Cheat Sheet}}}} \\ \normalsize{by \textcolor{DarkBackground}{nixik09} via \textcolor{DarkBackground}{\uline{cheatography.com/212204/cs/46107/}}} \end{tabulary} \end{multicols}} \fancyfoot[L]{ \footnotesize \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{LL} \SetRowColor{FootBackground} \mymulticolumn{2}{p{5.377cm}}{\bf\textcolor{white}{Cheatographer}} \\ \vspace{-2pt}nixik09 \\ \uline{cheatography.com/nixik09} \\ \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Cheat Sheet}} \\ \vspace{-2pt}Not Yet Published.\\ Updated 16th April, 2025.\\ Page {\thepage} of \pageref{LastPage}. \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Sponsor}} \\ \SetRowColor{white} \vspace{-5pt} %\includegraphics[width=48px,height=48px]{dave.jpeg} Measure your website readability!\\ www.readability-score.com \end{tabulary} \end{multicols}} \begin{document} \raggedright \raggedcolumns % Set font size to small. Switch to any value % from this page to resize cheat sheet text: % www.emerson.emory.edu/services/latex/latex_169.html \footnotesize % Small font. \begin{multicols*}{2} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Data types in Java}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{\{\{border=3\}\}{\bf{Type}}} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{byte} \tn % Row Count 2 (+ 1) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{short} \tn % Row Count 3 (+ 1) % Row 3 \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{int} \tn % Row Count 4 (+ 1) % Row 4 \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{long} \tn % Row Count 5 (+ 1) % Row 5 \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{float} \tn % Row Count 6 (+ 1) % Row 6 \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{double} \tn % Row Count 7 (+ 1) % Row 7 \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{char} \tn % Row Count 8 (+ 1) % Row 8 \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{boolean} \tn % Row Count 9 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Checked and unchecked exceptions and errors}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{Why "(un)checked"? Compiler can't anticipate logical errors that arise only at runtime, can't {\emph{check}} for those types of problems -{}-\textgreater{}"unchecked exceptions". Typically unchecked comes from logical errors/faulty logic that can occur anywhere.} \tn % Row Count 5 (+ 5) % Row 1 \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{{\bf{Checked Exceptions}}} \tn % Row Count 6 (+ 1) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{- Exceptional conditions that an app should anticipate and recover from.} \tn % Row Count 8 (+ 2) % Row 3 \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{- E.g. `FileNotFoundException` occurs when a method is trying to read a file that does not exist} \tn % Row Count 10 (+ 2) % Row 4 \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{- Checked at compile time - should be stated in method signature if throwing an exception. If exception could potentially be thrown in code, must handle it too.} \tn % Row Count 14 (+ 4) % Row 5 \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{Does not inherit from `RuntimeException` or `Error`? then its a {\bf{checked exception}}} \tn % Row Count 16 (+ 2) % Row 6 \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{{\bf{Unchecked Exceptions}}} \tn % Row Count 17 (+ 1) % Row 7 \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{- Exceptional conditions that app cannot anticipate/recover from} \tn % Row Count 19 (+ 2) % Row 8 \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{- E.g. is `NullPointerException` - when method is expecting non-null value but receives null.} \tn % Row Count 21 (+ 2) % Row 9 \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{- Not checked at compile time. Not required to be in method sig, not required to be handle it in code.} \tn % Row Count 24 (+ 3) % Row 10 \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{Is inherited from `RuntimeException`? then its an {\bf{unchecked exception}}} \tn % Row Count 26 (+ 2) % Row 11 \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{{\bf{Errors}}} \tn % Row Count 27 (+ 1) % Row 12 \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{E.g. `OutOfMemoryError` - when app is trying to use more memory than avail on system} \tn % Row Count 29 (+ 2) % Row 13 \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{- Not checked at compile time and not usually thrown from app code.} \tn % Row Count 31 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Switch statements}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{String direction = getDirection(); \newline switch (direction) \{ \newline case "left": \newline goLeft(); \newline break; \newline case "right": \newline goRight(); \newline break; \newline default: \newline return "unknown"; \newline \} \newline \newline // Java 14+ \newline return switch (shirtNum) \{ \newline case 1 -\textgreater{} "goalie"; \newline case 2 -\textgreater{} "left back"; \newline case 3, 4 -\textgreater{} "centre back"; \newline case 6, 7, 8 -\textgreater{} "midfielder"; \newline default -\textgreater{} throw new \seqsplit{IllegalArgumentException("Invalid} shirt number: " + shirtNum); \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{- Default case optional, but largely good practice to include one} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{x{3.76 cm} x{4.24 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Streams}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{- represents {\emph{sequence of elements}} and operating on those elements. Not data structures but take input from collections, arrays, or I/O channels.} \tn % Row Count 3 (+ 3) % Row 1 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{- key benefits: declarative, readable code; parallel operations; builtin operations; less boilerplate} \tn % Row Count 6 (+ 3) % Row 2 \SetRowColor{LightBackground} {\bf{Creating from a collection}} & List\textless{}String\textgreater{} list = \seqsplit{Arrays.asList("apple"}, "banana", "cherry");\{\{nl\}\}Stream\textless{}String\textgreater{} streamFromList = list.stream(); \tn % Row Count 12 (+ 6) % Row 3 \SetRowColor{white} {\bf{Creating a stream from an array}} & String{[}{]} array = \{"apple", "banana", "cherry"\};\{\{nl\}\} Stream\textless{}String\textgreater{} streamFromArray = \seqsplit{Arrays.stream(array);} \tn % Row Count 18 (+ 6) % Row 4 \SetRowColor{LightBackground} {\bf{Creating stream using Stream.of}} & Stream\textless{}String\textgreater{} streamOfElements = Stream.of("apple", "banana", "cherry"); \tn % Row Count 22 (+ 4) % Row 5 \SetRowColor{white} {\bf{Creating empty stream}} & Stream\textless{}String\textgreater{} emptyStream = Stream.empty(); \tn % Row Count 25 (+ 3) % Row 6 \SetRowColor{LightBackground} {\bf{Creating infinite streams}} & Stream\textless{}Integer\textgreater{} infiniteStream = Stream.iterate(0, n -\textgreater{} n + 1); \tn % Row Count 28 (+ 3) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Primitive streams}} \tn \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{{\bf{`mapToInt()` vs `map()`}} \newline % Row Count 1 (+ 1) - `map(String::length)` returns a `Stream\textless{}Integer\textgreater{}` (stream of `Integer` objects) \newline % Row Count 3 (+ 2) - \seqsplit{`mapToInt(String::length)`} returns an `IntStream` (stream of primitive `int`s) \newline % Row Count 5 (+ 2) {\bf{Specialised primitive streams}} \newline % Row Count 6 (+ 1) - `IntStream`, `LongStream`, `DoubleStream` \newline % Row Count 7 (+ 1) These streams have additional operations not available on regular streams: \newline % Row Count 9 (+ 2) - sum: `intStream.sum()` \newline % Row Count 10 (+ 1) - average: `intStream.average()` \newline % Row Count 11 (+ 1) - statistics: \seqsplit{`intStream.summaryStatistics()`} \newline % Row Count 12 (+ 1) Using primitive streams avoids boxing/unboxing overhead when dealing with numeric operations% Row Count 14 (+ 2) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Another stream ex.}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{List\textless{}Person\textgreater{} people = Arrays.asList( \newline new Person("John", 25), \newline new Person("Sarah", 32), \newline new Person("Mike", 17), \newline new Person("Emily", 25) \newline ); \newline \newline // Find names of adults, sorted alphabetically \newline List\textless{}String\textgreater{} adultNames = person.stream() \newline .filter(person -\textgreater{} person.getAge() \textgreater{}= 18) \newline .map(Person::getName) \newline .sorted() \newline \seqsplit{.collect(Collectors.toList());} \newline \newline System.out.println(adultNames); // {[}Emily, John, Sarah{]} \newline \newline double averageAge = people.stream() \newline \seqsplit{.mapToInt(Person::getAge)} \newline .average() \newline .orElse(0.0); \newline \newline System.out.println("Average age: " + averageAge);} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{x{1.748 cm} x{2.888 cm} x{2.964 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{8.4cm}}{\bf\textcolor{white}{Method references}} \tn % Row 0 \SetRowColor{LightBackground} Syntax & Equivalent Lambda & Meaning \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} \seqsplit{object::instanceMethod} & x -\textgreater{} \seqsplit{object.instanceMethod(x)} & Use object as the target for each call \tn % Row Count 5 (+ 3) % Row 2 \SetRowColor{LightBackground} \seqsplit{Class::staticMethod} & x -\textgreater{} \seqsplit{Class.staticMethod(x)} & Call a static method \tn % Row Count 8 (+ 3) % Row 3 \SetRowColor{white} \seqsplit{Class::instanceMethod} & (obj, arg) -\textgreater{} \seqsplit{obj.instanceMethod(arg)} & Useful in sorting or grouping \tn % Row Count 11 (+ 3) \hhline{>{\arrayrulecolor{DarkBackground}}---} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Concurrency: creating threads}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{// 1. by inheriting from Thread class \newline public class ExampleThread extends Thread \{ \newline @Override // note override! invoked when thread starts \newline public void run() \{ // we do NOT call RUN!! \newline // contains all the code to execute when starting thread \newline \seqsplit{System.out.println(Thread.currentThread().getName());} \newline \} \newline \} \newline \newline // start new thread.. \newline public class ThreadExamples \{ \newline public static void main(String{[}{]} args ) \{ \newline ExampleThread thread = new ExampleThread(); \newline thread.start(); // only START to start new thread \newline \} \newline \} \newline \newline // 2. implementing Runnable interface \newline public class ExampleRunnable implements Runnable \{ \newline @Override // note OVERRIDE!! \newline public void run() \{ \newline \seqsplit{System.out.println(Thread.currentThread().getName());} \newline \} \newline \} \newline \newline public class ThreadExamples \{ \newline public static void main(String{[}{]} args) \{ \newline ExampleRunnable runnable = new ExampleRunnable(); \newline Thread thread = new Thread(runnable); \newline thread.start(); \newline \} \newline \} \newline \newline // 3. Anon declarations \newline public class Main \{ \newline public static void main(String{[}{]} args) \{ \newline Thread thread = new Thread(() -\textgreater{} \{ \newline \seqsplit{System.out.println(Thread.currentThread().getName());} \newline \}); \newline thread.start(); \newline \} \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{Both 1) and 2) work exactly the same with no diff in performance. BUT, Runnable interfaces leaves option of extending class with some other class since you can inherit only one class in Java. Also, easier to create a thread pool using runnables.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Throwing and handling exceptions}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{/{\bf{\{\{lang-java\}\} \newline {\emph{Throwing a }}checked{\bf{ exception}} \newline {\emph{/ \newline public class \seqsplit{InsufficientBalanceException} extends Exception \{\} \newline \newline public class BankAccount \{ \newline public void withdraw(double amount) throws \seqsplit{InsufficientBalanceException} \{ \newline if (balance \textless{} amount) \{ \newline throw new \seqsplit{InsufficientBalanceException();} \newline \} \newline \} \newline \newline /}} \newline }}Throwing an {\bf{unchecked}} exception{\emph{ \newline }}/ \newline public class BankAccount \{ \newline public void withdraw(double amount) \{ \newline if (amount \textless{} 0) \{ \newline throw new \seqsplit{IllegalArgumentException("Cannot} withdraw a negative amount"); \newline \} \newline \} \newline \} \newline \newline /{\bf{ \newline }}{\emph{try, catch and finally}}{\emph{* \newline }}/ \newline try \{ \newline \seqsplit{bankAccount.withdraw(amount);} \newline \} catch \seqsplit{(InsufficientBalanceException)} \{ \newline \seqsplit{System.out.println("Withdrawal} failed: insufficient balance"); \newline \} catch (RuntimeException e) \{ \newline \seqsplit{System.out.println("Withdrawal} failed: " + e.getMessage()); \newline \} finally \{ \newline \seqsplit{System.out.println("Current} balance: " + \seqsplit{bankAccount.getBalance());} \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{x{3.68 cm} x{4.32 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Java Maps}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{dictionary DS - HashMap, TreeMap} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{Map\textless{}String, Integer\textgreater{} fruitPrices = new HashMap\textless{}\textgreater{}();} \tn % Row Count 3 (+ 2) % Row 2 \SetRowColor{LightBackground} Add entries & \seqsplit{fruitPrices.put("apple"}, 100); \tn % Row Count 5 (+ 2) % Row 3 \SetRowColor{white} Get value for a key & \seqsplit{fruitPrices.get("apple");} \tn % Row Count 7 (+ 2) % Row 4 \SetRowColor{LightBackground} Check if map contains specific key & \seqsplit{fruitPrices.containsKey("apple");} // =\textgreater{} true \tn % Row Count 10 (+ 3) % Row 5 \SetRowColor{white} Remove entries & \seqsplit{fruitPrices.remove("plum");} \tn % Row Count 12 (+ 2) % Row 6 \SetRowColor{LightBackground} Get size & fruitPrices.size(); \tn % Row Count 13 (+ 1) % Row 7 \SetRowColor{white} Get all keys in map & \seqsplit{fruitPrices.keySet();} // returns keys in a set \tn % Row Count 16 (+ 3) % Row 8 \SetRowColor{LightBackground} Get all values in map & \seqsplit{fruitPrices.values();} // returns values in a collection \tn % Row Count 19 (+ 3) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Stream intermediate operations}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{List\textless{}String\textgreater{} fruits = Arrays.asList("apple", "banana", "cherry", "date"); \newline \newline // filter - keeps elements that match a predicate \newline Stream\textless{}String\textgreater{} longFruits = fruits.stream() \newline .filter(fruit -\textgreater{} fruit.length() \textgreater{} 5); \newline \newline // map - transforms each element \newline Stream\textless{}String\textgreater{} fruitLengths = fruits.stream() \newline .map(String::length); \newline \newline // sorted - sorts elements \newline Stream\textless{}String\textgreater{} sortedFruits = fruits.stream() \newline .sorted(); \newline \newline // distinct - removes duplicates \newline Stream\textless{}String\textgreater{} uniqueFruits = fruits.stream() \newline .distinct(); \newline \newline // limit - reduces stream size \newline Stream\textless{}String\textgreater{} limitedFruits = fruits.stream() \newline .limit(2); \newline \newline // skip - skips elements \newline Stream\textless{}String\textgreater{} skippedFruits = fruits.stream() \newline .skip(1);} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{- These return a new stream and are lazy for performance reasons \newline - Allows JVM to optimise entire operation chain at once \newline - For ex., if you filter 1000 elements and then limit to 5, Java can stop processing after finding 5 elements that match the filter (rather than filtering all 1000 first).} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Stream terminal operations}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{List\textless{}String\textgreater{} fruits = Arrays.asList("apple", "banana", "cherry"); \newline \newline // forEach - performs actions on each element \newline fruits.stream().forEach(System.out::println); \newline \newline // collect - puts each element into a collection \newline List\textless{}String\textgreater{} fruitList = fruits.stream() \newline .filter(fruit -\textgreater{} fruit.length() \textgreater{} 5) \newline \seqsplit{.collect(Collectors.toList());} \newline \newline // reduce - reduces stream to single value \newline Optional\textless{}String\textgreater{} combined = fruits.stream() \newline .reduce((a, b) -\textgreater{} a + ", " + b); \newline \newline // count - returns number of elements \newline long count = fruits.stream().count(); \newline \newline // \seqsplit{anyMatch/allMatch/noneMatch} - check predicates \newline boolean anyLong = fruits.stream() \newline .anyMatch(fruit -\textgreater{} fruit.length() \textgreater{} 5); \newline boolean allLong = fruits.stream() \newline .allMatch(fruit -\textgreater{} fruit.length() \textgreater{} 3); \newline boolean noneLong = fruits.stream() \newline .noneMatch(fruit -\textgreater{} fruit.length() \textgreater{} 10); \newline \newline // findFirst/findAny - find elements \newline Optional\textless{}String\textgreater{} first = \seqsplit{fruits.stream().findFirst();}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{- These are terminal - they {\bf{don't return a stream}} but {\bf{return a concrete result or side-effect}} (e.g. collection, primitive or object). \newline - They trigger the actual processing of stream elements - note above collect() returning a collection, count() returning a long, reduce() returning an Optional/specific value or forEach() returning void (producing side effects). \newline - `average()` - operation on `IntStream` - returns OptionalDouble} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Method references code samples}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{- String::length and x::equals - not static methods; equals() and length() are both instance methods. \newline - The shorthand forms are method references, equivalent to x -\textgreater{} operation.equals(x) or x-\textgreater{}x.length. \newline \newline //{\bf{{\emph{`object::instanceMethod`}}}} \newline `String prefix = "Hello";` \newline `List\textless{}String\textgreater{} words = List.of("Hello", "Hi", "Hey"); ` \newline `boolean allMatch = words.stream()` \newline ` \seqsplit{.allMatch(prefix::equals);} // same: x -\textgreater{} prefix.equals(x)` \newline \newline //{\bf{{\emph{`Class::staticMethod`}}}} \newline // Use for static utility methods, like from Math or Integer \newline `List\textless{}String\textgreater{} numbers = List.of("1", "2", "3");` \newline `List\textless{}Integer\textgreater{} ints = numbers.stream()` \newline ` .map(Integer::parseInt) // same as: x -\textgreater{} Integer.parseInt(x)` \newline ` .toList();` \newline \newline `List\textless{}Double\textgreater{} values = List.of(9.0, 16.0, 25.0);` \newline `List\textless{}Double\textgreater{} roots = values.stream()` \newline ` .map(Math::sqrt) // same as: x -\textgreater{} Math.sqrt(x)` \newline ` .toList();` \newline \newline //{\bf{{\emph{`Class::instanceMethod`}}}} \newline `List\textless{}String\textgreater{} items = List.of("Hello", "Hi", "Hey"); ` \newline `List\textless{}String\textgreater{} lower = items.stream()` \newline ` \seqsplit{.map(String::toUpperCase)} // same as: x -\textgreater{} s -\textgreater{} s.toUpperCase()` \newline ` .toList();` \newline \newline `List\textless{}String\textgreater{} nonEmpty = items.stream()` \newline ` .filter(s -\textgreater{} !s.isEmpty()); // classic` \newline // or \newline `List\textless{}String\textgreater{} nonEmpty2 = items.stream()` \newline \seqsplit{.filter(Predicate.not(String::isEmpty))} // java 11+ \newline .toList(); \newline \newline //{\bf{{\emph{`Constructor references - ClassName::new`}}}} \newline `List\textless{}String\textgreater{} list = Stream.of("a", "b", "c")` \newline ` \seqsplit{.collect(Collectors.toCollection(ArrayList::new));} // creates new ArrayList` \newline \newline //{\bf{{\emph{`Sorting with method references`}}}} \newline List\textless{}String\textgreater{} names = List.of("Zoe", "Amy", "John"); \newline `List\textless{}String\textgreater{} sorted = names.stream()` \newline ` \seqsplit{.sorted(String::compareToIgnoreCase)} // same as (a, b) -\textgreater{} \seqsplit{a.compareToIgnoreCase(b)`} \newline ` .toList();`} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{x{1.824 cm} x{2.66 cm} x{3.116 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{8.4cm}}{\bf\textcolor{white}{Concurrency terms}} \tn % Row 0 \SetRowColor{LightBackground} {\bf{Concept}} & {\bf{Analogy}} & {\bf{Java Tool}} \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} Thread & A separate worker & Thread, Runnable, Callable \tn % Row Count 4 (+ 2) % Row 2 \SetRowColor{LightBackground} Race \seqsplit{condition} & Two people grabbing same sandwich & synchronized, locks, Atomic* \tn % Row Count 7 (+ 3) % Row 3 \SetRowColor{white} Thread pool & Team of workers managed by boss & ExecutorService \tn % Row Count 10 (+ 3) % Row 4 \SetRowColor{LightBackground} Results from a thread & Waiter bringing back your order & Future, Callable \tn % Row Count 13 (+ 3) % Row 5 \SetRowColor{white} \seqsplit{Thread-safe} \seqsplit{collections} & & \seqsplit{ConcurrentHashMap}, \seqsplit{CopyOnWriteArrayList} \tn % Row Count 16 (+ 3) % Row 6 \SetRowColor{LightBackground} \mymulticolumn{3}{x{8.4cm}}{Concurrency: tasks appear to run at the same time, but may take turns sharing resources} \tn % Row Count 18 (+ 2) % Row 7 \SetRowColor{white} \mymulticolumn{3}{x{8.4cm}}{Parallelism: Tasks actually run at the same time on different cores} \tn % Row Count 20 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}---} \end{tabularx} \par\addvspace{1.3em} % That's all folks \end{multicols*} \end{document}