{"id":13495053,"url":"https://github.com/BafS/Java8-CheatSheet","last_synced_at":"2025-03-28T16:31:10.624Z","repository":{"id":33961201,"uuid":"37693250","full_name":"BafS/Java8-CheatSheet","owner":"BafS","description":"A Java 8+ Cheat Sheet for functional programming","archived":false,"fork":false,"pushed_at":"2023-10-02T08:35:21.000Z","size":24,"stargazers_count":501,"open_issues_count":0,"forks_count":176,"subscribers_count":18,"default_branch":"master","last_synced_at":"2025-03-23T04:02:43.001Z","etag":null,"topics":["cheatsheet","functional-programming","java","java8","lambda-expressions","memo","resume","stream"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"dav/word2vec","license":"gpl-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/BafS.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2015-06-19T00:41:21.000Z","updated_at":"2024-12-26T07:07:06.000Z","dependencies_parsed_at":"2024-01-18T09:56:44.609Z","dependency_job_id":"6c1b0d61-59b1-4452-b8d7-8fb3329683c1","html_url":"https://github.com/BafS/Java8-CheatSheet","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BafS%2FJava8-CheatSheet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BafS%2FJava8-CheatSheet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BafS%2FJava8-CheatSheet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BafS%2FJava8-CheatSheet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/BafS","download_url":"https://codeload.github.com/BafS/Java8-CheatSheet/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246062676,"owners_count":20717679,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cheatsheet","functional-programming","java","java8","lambda-expressions","memo","resume","stream"],"created_at":"2024-07-31T19:01:30.755Z","updated_at":"2025-03-28T16:31:10.476Z","avatar_url":"https://github.com/BafS.png","language":null,"readme":"\n# JAVA 8 - Cheat Sheet\n\n## Lambda Expression\n\n```java\n(int a) -\u003e a * 2; // Calculate the double of a\na -\u003e a * 2; // or simply without type\n```\n\n```java\n(a, b) -\u003e a + b; // Sum of 2 parameters\n```\n\nIf the lambda is more than one expression we can use `{ }` and `return`\n\n```java\n(x, y) -\u003e {\n    int sum = x + y;\n    int avg = sum / 2;\n    return avg;\n}\n```\n\nA lambda expression cannot stand alone in Java, it need to be associated to a functional interface.\n\n```java\ninterface MyMath {\n    int getDoubleOf(int a);\n}\n\nMyMath d = a -\u003e a * 2; // associated to the interface\nd.getDoubleOf(4); // is 8\n```\n\n---\n\nAll examples with \"list\" use :\n\n```java\nList\u003cString\u003e list = [Bohr, Darwin, Galilei, Tesla, Einstein, Newton]\n```\n\n\n## Collections\n\n**sort** `sort(list, comparator)`\n\n```java\nlist.sort((a, b) -\u003e a.length() - b.length())\nlist.sort(Comparator.comparing(n -\u003e n.length())); // same\nlist.sort(Comparator.comparing(String::length)); // same\n//\u003e [Bohr, Tesla, Darwin, Newton, Galilei, Einstein]\n```\n\n**removeIf**\n\n```java\nlist.removeIf(w -\u003e w.length() \u003c 6);\n//\u003e [Darwin, Galilei, Einstein, Newton]\n```\n\n**merge**\n`merge(key, value, remappingFunction)`\n\n```java\nMap\u003cString, String\u003e names = new HashMap\u003c\u003e();\nnames.put(\"Albert\", \"Ein?\");\nnames.put(\"Marie\", \"Curie\");\nnames.put(\"Max\", \"Plank\");\n\n// Value \"Albert\" exists\n// {Marie=Curie, Max=Plank, Albert=Einstein}\nnames.merge(\"Albert\", \"stein\", (old, val) -\u003e old.substring(0, 3) + val);\n\n// Value \"Newname\" don't exists\n// {Marie=Curie, Newname=stein, Max=Plank, Albert=Einstein}\nnames.merge(\"Newname\", \"stein\", (old, val) -\u003e old.substring(0, 3) + val);\n```\n\n\n## Method Expressions `Class::staticMethod`\n\nAllows to reference methods (and constructors) without executing them\n\n```java\n// Lambda Form:\ngetPrimes(numbers, a -\u003e StaticMethod.isPrime(a));\n\n// Method Reference:\ngetPrimes(numbers, StaticMethod::isPrime);\n```\n\n| Method Reference | Lambda Form |\n| ---------------- | ----------- |\n| `StaticMethod::isPrime` | `n -\u003e StaticMethod.isPrime(n)` |\n| `String::toUpperCase`   | `(String w) -\u003e w.toUpperCase()` |\n| `String::compareTo`     | `(String s, String t) -\u003e s.compareTo(t)` |\n| `System.out::println`   | `x -\u003e System.out.println(x)` |\n| `Double::new`           | `n -\u003e new Double(n)` |\n| `String[]::new`         | `(int n) -\u003e new String[n]` |\n\n\n## Streams\n\nSimilar to collections, but\n\n - They don't store their own data\n - The data comes from elsewhere (collection, file, db, web, ...)\n - *immutable* (produce new streams)\n - *lazy* (only computes what is necessary !)\n \n```java\n// Will compute just 3 \"filter\"\nStream\u003cString\u003e longNames = list\n   .filter(n -\u003e n.length() \u003e 8)\n   .limit(3);\n```\n\n**Create a new stream**\n\n```java\nStream\u003cInteger\u003e stream = Stream.of(1, 2, 3, 5, 7, 11);\nStream\u003cString\u003e stream = Stream.of(\"Jazz\", \"Blues\", \"Rock\");\nStream\u003cString\u003e stream = Stream.of(myArray); // or from an array\nStream\u003cString\u003e stream = list.stream(); // or from a list\n\n// Infinit stream [0; inf[\nStream\u003cInteger\u003e integers = Stream.iterate(0, n -\u003e n + 1);\n```\n\n**Collecting results**\n\n```java\n// Collect into an array (::new is the constructor reference)\nString[] myArray = stream.toArray(String[]::new);\n\n// Collect into a List or Set\nList\u003cString\u003e myList = stream.collect(Collectors.toList());\nSet\u003cString\u003e mySet = stream.collect(Collectors.toSet());\n\n// Collect into a String\nString str = list.collect(Collectors.joining(\", \"));\n```\n\n**map** `map(mapper)`\u003cbr\u003e\nApplying a function to each element\n\n```java\n// Apply \"toLowerCase\" for each element\nStream\u003cString\u003e res = stream.map(w -\u003e w.toLowerCase());\nStream\u003cString\u003e res = stream.map(String::toLowerCase);\n//\u003e bohr darwin galilei tesla einstein newton\n\nStream\u003cInteger\u003e res = Stream.of(1, 2, 3, 4, 5).map(x -\u003e x + 1);\n//\u003e 2 3 4 5 6\n```\n\n**filter** `filter(predicate)`\u003cbr\u003e\nRetains elements that match the predicate\n\n```java\n// Filter elements that begin with \"E\"\nres = stream.filter(n -\u003e n.substring(0, 1).equals(\"E\"));\n//\u003e Einstein\n\nres = Stream.of(1, 2, 3, 4, 5).filter(x -\u003e x \u003c 3);\n//\u003e 1 2\n```\n\n**reduce**\u003cbr\u003e\nReduce the elements to a single value\n\n```java\nString reduced = stream.reduce(\"\", (acc, el) -\u003e acc + \"|\" + el);\n//\u003e |Bohr|Darwin|Galilei|Tesla|Einstein|Newton\n```\n\n**limit** `limit(maxSize)`\u003cbr\u003e\nSelect the n first elements\n\n```java\nres = stream.limit(3);\n//\u003e Bohr Darwin Galilei\n```\n\n**skip**\u003cbr\u003e\nDiscarding the first n elements\n\n```java\nres = stream.skip(2); // skip Bohr and Darwin\n//\u003e Galilei Tesla Einstein Newton\n```\n\n**distinct**\u003cbr\u003e\nRemove duplicated elemetns\n\n```java\nres = Stream.of(1, 0, 0, 1, 0, 1).distinct();\n//\u003e 1 0\n```\n\n**sorted**\u003cbr\u003e\nSort elements (must be *Comparable*)\n\n```java\nres = stream.sorted();\n//\u003e Bohr Darwin Einstein Galilei Newton Tesla \n```\n\n**allMatch** / **noneMatch**\n\n```java\n// Check if there is a \"e\" in each elements\nboolean res = words.allMatch(n -\u003e n.contains(\"e\"));\n```\n\nanyMatch: Check if there is a \"e\" in an element\u003cbr\u003e\nnoneMatch: Check if there is no \"e\" in elements\n\n**parallel**\u003cbr\u003e\nReturns an equivalent stream that is parallel\n\n**findAny**\u003cbr\u003e\nfaster than findFirst on parallel streams\n\n### Primitive-Type Streams\n\nWrappers (like Stream\u003cInteger\u003e) are inefficients. It requires a lot of unboxing and boxing for each element. Better to use `IntStream`, `DoubleStream`, etc.\n\n**Creation**\n\n```java\nIntStream stream = IntStream.of(1, 2, 3, 5, 7);\nstream = IntStream.of(myArray); // from an array\nstream = IntStream.range(5, 80); // range from 5 to 80\n\nRandom gen = new Random();\nIntStream rand = gen(1, 9); // stream of randoms\n```\n\nUse *mapToX* (mapToObj, mapToDouble, etc.) if the function yields Object, double, etc. values.\n\n### Grouping Results\n\n**Collectors.groupingBy**\n\n```java\n// Groupe by length\nMap\u003cInteger, List\u003cString\u003e\u003e groups = stream.collect(Collectors.groupingBy(w -\u003e w.length()));\n//\u003e {4=[Bohr], 5=[Tesla], 6=[Darwin, Newton], 7=[Galilei], 8=[Einstein]}\n```\n\n**Collectors.toSet**\n\n```java\n// Same as before but with Set\nMap\u003cString, Set\u003cString\u003e\u003e groups2 = stream.collect(Collectors.groupingBy(w -\u003e w.substring(0, 1), Collectors.toSet()));\n//\u003e {B=[Bohr], T=[Tesla], D=[Darwin], E=[Einstein], G=[Galilei], N=[Newton]}\n```\n\n**Collectors.counting**\u003cbr\u003e\nCount the number of values in a group\n\n**Collectors.summing__**\u003cbr\u003e\n`summingInt`, `summingLong`, `summingDouble` to sum group values\n\n**Collectors.averaging__**\u003cbr\u003e\n`averagingInt`, `averagingLong`, ... to average group values\n\n```java\n// Average length of each element of a group\nCollectors.averagingInt(String::length)\n```\n\n*PS*: Don't forget Optional (like `Map\u003cT, Optional\u003cT\u003e\u003e`) with some Collection methods (like `Collectors.maxBy`).\n\n\n### Parallel Streams\n\n**Creation**\n\n```java\nStream\u003cString\u003e parStream = list.parallelStream();\nStream\u003cString\u003e parStream = Stream.of(myArray).parallel();\n```\n\n**unordered**\nCan speed up the `limit` or `distinct`\n\n```java\nstream.parallelStream().unordered().distinct();\n```\n\n*PS*: Work with the streams library. Eg. use `filter(x -\u003e x.length() \u003c 9)` instead of a `forEach` with an `if`.\n\n\n## Optional\n\nIn Java, it is common to use null to denote absence of result.\u003cbr\u003e\nProblems when no checks: `NullPointerException`.\n\n```java\n// Optional\u003cString\u003e contains a string or nothing\nOptional\u003cString\u003e res = stream\n   .filter(w -\u003e w.length() \u003e 10)\n   .findFirst();\n\n// length of the value or \"\" if nothing\nint length = res.orElse(\"\").length();\n\n// run the lambda if there is a value\nres.ifPresent(v -\u003e results.add(v));\n```\n\nReturn an Optional\n\n```java\nOptional\u003cDouble\u003e squareRoot(double x) {\n   if (x \u003e= 0) { return Optional.of(Math.sqrt(x)); }\n   else { return Optional.empty(); }\n}\n```\n\n---\n\n**Note on inferance limitations**\n\n```java\ninterface Pair\u003cA, B\u003e {\n    A first();\n    B second();\n}\n```\n\nA steam of type `Stream\u003cPair\u003cString, Long\u003e\u003e` :\n- `stream.sorted(Comparator.comparing(Pair::first)) // ok`\n- `stream.sorted(Comparator.comparing(Pair::first).thenComparing(Pair::second)) // dont work`\n\nJava cannot infer type for the `.comparing(Pair::first)` part and fallback to Object, on which `Pair::first` cannot be applied.\n\nThe required type for the whole expression cannot be propagated through the method call (`.thenComparing`) and used to infer type of the first part.\n\nType *must* be given explicitly.\n\n```java\nstream.sorted(\n    Comparator.\u003cPair\u003cString, Long\u003e, String\u003ecomparing(Pair::first)\n    .thenComparing(Pair::second)\n) // ok\n```\n\n---\n\nThis cheat sheet was based on the lecture of Cay Horstmann\nhttp://horstmann.com/heig-vd/spring2015/poo/\n","funding_links":[],"categories":["Others","Programming Languages"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FBafS%2FJava8-CheatSheet","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FBafS%2FJava8-CheatSheet","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FBafS%2FJava8-CheatSheet/lists"}