├── .gitignore ├── Compare.java ├── D.java ├── FilesTest.java ├── Func.java ├── Functions.java ├── Grouping.java ├── Hello.java ├── Iface.java ├── LICENSE ├── Lists.java ├── Nashorn.java ├── Nio.java ├── Parenting.java ├── Patt.java ├── README.md ├── Rand.java ├── Sort.java ├── Streams.java ├── Tail.java ├── TailTest.java ├── Temporal.java ├── ThreeTen.java ├── Twoface.java ├── Zones.java ├── arr.js ├── concurrent.js ├── hello.js ├── imports.js ├── jc8.sh ├── jjs.sh ├── paths.js ├── sum.js └── sum2.js /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | *~ 3 | 4 | # Package Files # 5 | *.jar 6 | *.war 7 | *.ear 8 | -------------------------------------------------------------------------------- /Compare.java: -------------------------------------------------------------------------------- 1 | import java.awt.event.ActionEvent; 2 | import java.awt.event.ActionListener; 3 | import java.util.Arrays; 4 | import java.util.Collections; 5 | import java.util.Comparator; 6 | import java.util.List; 7 | import java.util.stream.IntStream; 8 | import java.util.stream.Stream; 9 | 10 | /** 11 | * Compares Java 7 code to Java 8 equivalent. 12 | * 13 | * @author adavis 14 | */ 15 | public class Compare { 16 | 17 | public String toString() { 18 | return "Hello!"; 19 | } 20 | 21 | public Runnable makeRunnable() { 22 | // Java 7 23 | Runnable r = new Runnable() { 24 | @Override 25 | public void run() { 26 | System.out.println(Compare.this.toString()); 27 | } 28 | }; 29 | // Java 8 30 | Runnable r8 = () -> System.out.println(toString()); 31 | 32 | return r8; 33 | } 34 | 35 | public ActionListener makeListener() { 36 | // Java 7 37 | ActionListener al = new ActionListener() { 38 | @Override 39 | public void actionPerformed(ActionEvent e) { 40 | System.out.println(e.getActionCommand()); 41 | } 42 | }; 43 | // Java 8 44 | ActionListener al8 = e -> System.out.println(e.getActionCommand()); 45 | 46 | return al8; 47 | } 48 | 49 | public List printStrings(List list) { 50 | // Java 7 51 | for (String s : list) { 52 | System.out.println(s); 53 | } 54 | //Java 8 55 | list.forEach(System.out::println); 56 | 57 | return list; 58 | } 59 | 60 | public List sortStrings(List list) { 61 | // Java 7 62 | Collections.sort(list, new Comparator() { 63 | @Override 64 | public int compare(String s1, String s2) { 65 | return s1.length() - s2.length(); 66 | } 67 | }); 68 | //Java 8 69 | Collections.sort(list, (s1, s2) -> s1.length() - s2.length()); 70 | // or 71 | list.sort(Comparator.comparingInt(String::length)); 72 | 73 | return list; 74 | } 75 | 76 | public double max(List list) { 77 | assert list.size() > 0; 78 | // Java 7 79 | double max = 0; 80 | 81 | for (Double d : list) { 82 | if (d > max) { 83 | max = d; 84 | } 85 | } 86 | //Java 8 87 | max = list.stream().reduce(0.0, Math::max); 88 | // or 89 | max = list.stream().mapToDouble(Number::doubleValue).max().getAsDouble(); 90 | 91 | return max; 92 | } 93 | 94 | public double average(List list) { 95 | assert list.size() > 0; 96 | double total = 0; 97 | double ave = 0; 98 | // Java 7 99 | for (Double d : list) { 100 | total += d; 101 | } 102 | ave = total / ((double) list.size()); 103 | //Java 8 104 | ave = list.stream().mapToDouble(Number::doubleValue).average().getAsDouble(); 105 | 106 | return ave; 107 | } 108 | 109 | public void print1to10() { 110 | // Java 7 111 | for (int i = 1; i < 11; i++) { 112 | System.out.println(i); 113 | } 114 | // Java 8 115 | IntStream.range(1, 11) 116 | .forEach(System.out::println); 117 | //or 118 | Stream.iterate(1, i -> i+1).limit(10) 119 | .forEach(System.out::println); 120 | } 121 | 122 | public static class Person { 123 | 124 | String firstName; 125 | String lastName; 126 | 127 | public String getFirstName() { 128 | return firstName; 129 | } 130 | 131 | public String getLastName() { 132 | return lastName; 133 | } 134 | } 135 | 136 | public List sortPeople(List list) { 137 | // Java 7 138 | Collections.sort(list, new Comparator() { 139 | @Override 140 | public int compare(Person p1, Person p2) { 141 | int n = p1.getLastName().compareTo(p2.getLastName()); 142 | if (n == 0) { 143 | return p1.getFirstName().compareTo(p2.getFirstName()); 144 | } 145 | return n; 146 | } 147 | }); 148 | //Java 8 149 | list.sort(Comparator.comparing(Person::getLastName) 150 | .thenComparing(Person::getFirstName)); 151 | 152 | return list; 153 | } 154 | 155 | public static void main(String ... args) { 156 | Compare c = new Compare(); 157 | 158 | c.makeRunnable().run(); 159 | System.out.println("---------------"); 160 | // List list = Arrays.asList("foo", "bar", "bash", "bo"); 161 | // c.sortStrings(list); 162 | // c.printStrings(list); 163 | // System.out.println("---------------"); 164 | // c.print1to10(); 165 | // System.out.println(c.max(Arrays.asList(0.1, 0.2, 0.21))); 166 | // System.out.println(c.average(Arrays.asList(0.1, 0.2, 0.21))); 167 | } 168 | 169 | } 170 | -------------------------------------------------------------------------------- /D.java: -------------------------------------------------------------------------------- 1 | import static java.util.stream.Collectors.*; 2 | import java.util.Arrays; 3 | 4 | public class D { 5 | 6 | public static void main(String...ags) { 7 | double[] dd = {1.0,2.0,3.0}; 8 | 9 | System.out.println( 10 | Arrays.stream(dd).max().getAsDouble() 11 | ); 12 | System.out.println( 13 | Arrays.stream(dd).average().getAsDouble() 14 | ); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /FilesTest.java: -------------------------------------------------------------------------------- 1 | import java.nio.file.*; 2 | import java.nio.*; 3 | import java.io.*; 4 | import java.util.stream.*; 5 | 6 | 7 | public class FilesTest { 8 | 9 | public static void main(String...args) throws IOException { 10 | 11 | Path path = Paths.get("Nio.java"); 12 | 13 | try (Stream st = Files.lines(path)) { 14 | st.forEach(System.out::println); 15 | } 16 | } 17 | } 18 | 19 | -------------------------------------------------------------------------------- /Func.java: -------------------------------------------------------------------------------- 1 | import static java.lang.System.out; 2 | import java.util.function.*; 3 | 4 | 5 | public class Func { 6 | 7 | 8 | static Function f = (name) -> {return name + "-";}; 9 | static Function leng = (name) -> {return name.length();}; 10 | static Function leng2 = String::length; 11 | //static Supplier ff = ()-> new Func(); 12 | 13 | public String name() { return "foo"; } 14 | 15 | public static void main(String ... args) { 16 | String[] strs = {"foo", "bar", "bash" }; 17 | 18 | for (String s : strs) out.println(leng.apply(s)); 19 | //for (String s : strs) out.println(leng2.apply(s)); 20 | 21 | Function name = Func::name; 22 | 23 | out.println(name.apply(new Func())); 24 | } 25 | 26 | } 27 | 28 | -------------------------------------------------------------------------------- /Functions.java: -------------------------------------------------------------------------------- 1 | import java.util.function.*; 2 | import java.util.stream.*; 3 | import static java.util.stream.Collectors.*; 4 | 5 | import java.time.*; 6 | 7 | 8 | public class Functions { 9 | 10 | public static void main(String...args) { 11 | 12 | Function f = Function.identity() 13 | .andThen(i -> 2*i).andThen(i -> "str" + i); 14 | 15 | System.out.println( 16 | Stream.iterate(1, i -> i + 1) 17 | .limit(10) 18 | .map(f) 19 | .collect(joining(",")) 20 | ); 21 | 22 | 23 | Function plusTwoM = Function.identity() 24 | .andThen(dateTimeFunction(d -> d.plusMonths(2))); 25 | 26 | System.out.println( 27 | Stream.iterate(LocalDate.now(), d -> d.plusDays(1)) 28 | .limit(10) 29 | .map(plusTwoM) 30 | .map(Object::toString) 31 | .collect(joining(", ")) 32 | ); 33 | } 34 | 35 | public static Function dateTimeFunction( 36 | final Function f) { 37 | 38 | return f.andThen(d -> d.atTime(2, 2)); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Grouping.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | import java.util.stream.*; 4 | import static java.util.stream.Collectors.*; 5 | 6 | public class Grouping { 7 | 8 | public static class Dragon { 9 | Dragon(String name) {this.name = name;} 10 | String name; 11 | public String getName() {return name; } 12 | public String toString() {return name; } 13 | public boolean isGreen() {return Math.random() > 0.5;} 14 | } 15 | 16 | public static List getDragons() { 17 | return Arrays.asList(new Dragon("Smaug"), new Dragon("Norbert"), new Dragon("Smoochy"), new Dragon("Nuvi")); 18 | } 19 | 20 | public static void main(String...args) { 21 | 22 | List dragons = getDragons(); 23 | Map> map = dragons.parallelStream() 24 | .collect(groupingByConcurrent(dragon -> dragon.getName().charAt(0))); 25 | 26 | System.out.println(map); 27 | 28 | Map> map2 = dragons.stream() 29 | .collect(partitioningBy(Dragon::isGreen)); 30 | 31 | 32 | System.out.println(map2); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Hello.java: -------------------------------------------------------------------------------- 1 | import static java.lang.System.out; 2 | 3 | public class Hello { 4 | Runnable r1 = () -> out.println(this); 5 | Runnable r2 = () -> out.println(toString()); 6 | 7 | public String toString() { return "Hello, world!"; } 8 | 9 | public static void main(String... args) { 10 | new Hello().r1.run(); //Hello, world! 11 | new Hello().r2.run(); //Hello, world! 12 | } 13 | } 14 | 15 | -------------------------------------------------------------------------------- /Iface.java: -------------------------------------------------------------------------------- 1 | public interface Iface { 2 | 3 | public static double random() { 4 | return Math.random(); 5 | } 6 | 7 | public default String getName() { 8 | return "name"; 9 | } 10 | 11 | /*public static void main(String...args) { 12 | System.out.println(Iface.random()); 13 | }//*/ 14 | } 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. -------------------------------------------------------------------------------- /Lists.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Lists { 4 | public static void main(String ... args) { 5 | List list = new LinkedList<>(); 6 | 7 | list.add("Smaug"); 8 | list.add("Gilda"); 9 | 10 | System.out.println(list); 11 | 12 | final StringBuilder userNames = new StringBuilder("("); 13 | 14 | for (String value : list) { 15 | if (userNames.length() > 1) { 16 | userNames.append(", "); 17 | } 18 | userNames.append('\'').append(value).append('\''); 19 | } 20 | userNames.append(')'); 21 | System.out.println(userNames); 22 | } 23 | }//END 24 | -------------------------------------------------------------------------------- /Nashorn.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import javax.script.Invocable; 3 | import javax.script.ScriptEngine; 4 | import javax.script.ScriptEngineManager; 5 | public class Nashorn { 6 | 7 | public static void main(String... args) throws Throwable { 8 | ScriptEngineManager engineManager = new ScriptEngineManager(); 9 | ScriptEngine engine = engineManager.getEngineByName("nashorn"); 10 | 11 | engine.eval("function p(s) { print(s) }"); 12 | engine.eval("p('Hello Nashorn');"); 13 | // engine.eval(new FileReader("hello.js")); 14 | // engine.eval(new FileReader("sum2.js")); 15 | // engine.eval(new FileReader("imports.js")); 16 | /* Invocable inv = (Invocable) engine; 17 | inv.invokeFunction("p", "hello"); 18 | JPrinter printer = inv.getInterface(JPrinter.class); 19 | printer.p("Hello again!"); 20 | //*/ 21 | } 22 | public static interface JPrinter { 23 | void p(String s); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Nio.java: -------------------------------------------------------------------------------- 1 | 2 | import static java.util.stream.Collectors.*; 3 | 4 | import java.util.stream.*; 5 | 6 | import java.nio.file.*; 7 | import java.nio.*; 8 | import java.io.*; 9 | import java.util.IntSummaryStatistics; 10 | 11 | public class Nio { 12 | 13 | public static void main(String...args) throws IOException { 14 | 15 | 16 | System.out.println("\n----->first 5 java file names:"); 17 | Files.list(Paths.get(".")) 18 | .map(Path::getFileName) // still a path 19 | .map(Path::toString) // convert to Strings 20 | .filter(name -> name.endsWith(".java")) 21 | .sorted() // sort them alphabetically 22 | .limit(5) // first 5 23 | .forEach(System.out::println); 24 | /* 25 | System.out.println("\n----->Print the code:"); 26 | 27 | Files.lines(Paths.get("Nio.java")) 28 | .map(String::trim) 29 | .filter(s -> !s.isEmpty()) 30 | .forEach(System.out::println); 31 | /*-/ 32 | System.out.println("\n----->Average line length:"); 33 | System.out.println( 34 | Files.lines(Paths.get("Nio.java")) 35 | .map(String::trim) 36 | .filter(s -> !s.isEmpty()) 37 | .collect(averagingInt(String::length)) 38 | ); 39 | IntSummaryStatistics stats = Files.lines(Paths.get("Nio.java")) 40 | .map(String::trim) 41 | .filter(s -> !s.isEmpty()) 42 | .collect(summarizingInt(String::length)); 43 | 44 | System.out.println(stats.getAverage()); 45 | System.out.println("count=" + stats.getCount()); 46 | System.out.println("max=" + stats.getMax()); 47 | System.out.println("min=" + stats.getMin()); 48 | */ 49 | /*String str = Stream.of("hello", "java", "8") 50 | .collect(joining("-")); 51 | System.out.println(str);*/ 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Parenting.java: -------------------------------------------------------------------------------- 1 | interface FlyingCreature { 2 | 3 | String getName(); 4 | 5 | default void fly() { 6 | System.out.println(getName() + " is flying"); 7 | } 8 | } 9 | 10 | abstract class NamedCreature { 11 | String name; 12 | public NamedCreature(String name) { 13 | this.name = name; 14 | } 15 | public String getName() { 16 | return name; 17 | } 18 | } 19 | 20 | class Griffon extends NamedCreature implements FlyingCreature { 21 | public Griffon(String n) { super(n); } 22 | } 23 | 24 | class Dragon extends NamedCreature implements FlyingCreature { 25 | public Dragon(String n) { super(n); } 26 | } 27 | 28 | public class Parenting { 29 | public static void main(String ... args) { 30 | Dragon d = new Dragon("Smaug"); 31 | Griffon g = new Griffon("Gilda"); 32 | d.fly(); // Smaug is flying 33 | g.fly(); // Gilda is flying 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Patt.java: -------------------------------------------------------------------------------- 1 | import java.util.regex.Pattern; 2 | 3 | public class Patt { 4 | public static void main(String...args) { 5 | Pattern patt = Pattern.compile("[, ]+"); 6 | patt.splitAsStream("a, b, c") 7 | .forEach(System.out::println); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | hellojava8 2 | ========== 3 | 4 | Code examples for java 8 talk 5 | -------------------------------------------------------------------------------- /Rand.java: -------------------------------------------------------------------------------- 1 | import java.util.Random; 2 | 3 | public class Rand { 4 | 5 | public static void main(String...args) { 6 | Random rnd = new Random(); 7 | rnd.ints().limit(10) 8 | .sorted() 9 | .forEach(System.out::println); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Sort.java: -------------------------------------------------------------------------------- 1 | import static java.lang.System.out; 2 | import java.util.Arrays; 3 | import java.util.Random; 4 | import java.util.stream.Stream; 5 | 6 | /** 7 | * Tests whether filtering before or after sorting makes a difference. 8 | * Spoiler-alert: it does. 9 | * 10 | * @author adamd 11 | */ 12 | public class Sort { 13 | 14 | public static long time(Runnable r) { 15 | long start = System.currentTimeMillis(); 16 | r.run(); 17 | return System.currentTimeMillis() - start; 18 | } 19 | 20 | // number of random numbers 21 | public static final int n = 123456; 22 | 23 | // just here to give algorithm something to modify... 24 | public static int sum = 0; 25 | 26 | public static long[] count = new long[3]; 27 | 28 | static final Random rnd = new Random(); 29 | 30 | public static void noFilter() { 31 | Stream.generate(() -> rnd.nextInt()).limit(n).sorted((x, y) -> { 32 | count[0]++; 33 | return x > y ? 1 : -1; 34 | }).forEach(x -> sum += x); 35 | } 36 | 37 | public static void filteredFirst() { 38 | Stream.generate(() -> rnd.nextInt()).limit(n).filter(x -> x > 0) 39 | .sorted((x, y) -> { 40 | count[1]++; 41 | return x > y ? 1 : -1; 42 | }).forEach(x -> sum += x); 43 | } 44 | 45 | public static void filteredSecond() { 46 | Stream.generate(() -> rnd.nextInt()).limit(n).sorted((x, y) -> { 47 | count[2]++; 48 | return x > y ? 1 : -1; 49 | }).filter(x -> x > 0).forEach(x -> sum += x); 50 | } 51 | 52 | public static void main(String... args) { 53 | Arrays.fill(count, 0); 54 | 55 | long t1 = time(Sort::noFilter); 56 | long t2 = time(Sort::filteredFirst); 57 | long t3 = time(Sort::filteredSecond); 58 | out.println("sum=" + sum); // meaningless 59 | out.println("t1=" + t1 + " count=" + count[0]); 60 | out.println("t2=" + t2 + " count=" + count[1]); 61 | out.println("t3=" + t3 + " count=" + count[2]); 62 | out.println("t1-t2 = " + ((double) (t1 - t2) / 1000.0) + " sec"); 63 | out.println("t1-t3 = " + ((double) (t1 - t3) / 1000.0) + " sec"); 64 | // time saved is probably negative or zero 65 | out.println("count diffs ="); 66 | out.println("noFilter - filter1st: " + (count[0] - count[1])); 67 | out.println("noFilter - filter2nd: " + (count[0] - count[2])); 68 | // if the diff is small then sorting happened before the filtering. 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /Streams.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.util.stream.*; 3 | import java.io.*; 4 | 5 | public class Streams { 6 | 7 | public static void write(FileWriter fw, String s) { 8 | try {fw.write(s); } 9 | catch (IOException e) {e.printStackTrace(); } 10 | } 11 | 12 | 13 | public static void main(String...args) throws IOException { 14 | try (FileWriter fw = new FileWriter("file")) { 15 | Stream.of("hello\n", "file\n").forEach(s -> write(fw, s)); 16 | } 17 | try (FileReader fr = new FileReader("file"); 18 | BufferedReader br = new BufferedReader(fr)) { 19 | br.lines().forEach(System.out::println); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Tail.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.stream.Stream; 3 | import java.math.*; 4 | 5 | /** 6 | * Implements tail-call using Java 8 Stream. 7 | * 8 | * @author adavis 9 | */ 10 | @FunctionalInterface 11 | public interface Tail { 12 | 13 | Tail apply(); 14 | 15 | default boolean isDone() { 16 | return false; 17 | } 18 | 19 | default T result() { 20 | throw new UnsupportedOperationException("Not done yet."); 21 | } 22 | 23 | default T invoke() { 24 | return Stream.iterate(this, Tail::apply) 25 | .filter(Tail::isDone) 26 | .findFirst() 27 | .get() 28 | .result(); 29 | } 30 | 31 | static Tail done(final T value) { 32 | return new Tail() { 33 | @Override 34 | public T result() { 35 | return value; 36 | } 37 | @Override 38 | public boolean isDone() { 39 | return true; 40 | } 41 | @Override 42 | public Tail apply() { 43 | throw new UnsupportedOperationException("Not supported."); 44 | } 45 | }; 46 | } 47 | 48 | static BigInteger streamFactorial(int n) { 49 | return streamFactorial(BigInteger.ONE, n).invoke(); 50 | } 51 | static Tail streamFactorial(BigInteger x, int n) { 52 | return () -> { 53 | switch (n) { 54 | case 1: 55 | return Tail.done(x); 56 | default: 57 | return streamFactorial(x.multiply(BigInteger.valueOf(n)), n - 1); 58 | } 59 | }; 60 | } 61 | 62 | static BigInteger stackFactorial(int n) { 63 | return stackFactorial(BigInteger.ONE, n); 64 | } 65 | static BigInteger stackFactorial(BigInteger x, int n) { 66 | if (n==1) return x; 67 | else return stackFactorial(x.multiply(BigInteger.valueOf(n)), n - 1); 68 | } 69 | 70 | public static void main(String...args) { 71 | long start = System.currentTimeMillis(); 72 | final int num = 55555; 73 | System.out.println("calculating " + num + "!"); 74 | try { 75 | stackFactorial(num); 76 | System.out.println("stack: " + (System.currentTimeMillis() - start)); 77 | } catch (StackOverflowError e) { 78 | System.err.println(e); 79 | } 80 | streamFactorial(num); 81 | System.out.println("stream: " + (System.currentTimeMillis() - start) + "ms"); 82 | } 83 | 84 | } 85 | 86 | -------------------------------------------------------------------------------- /TailTest.java: -------------------------------------------------------------------------------- 1 | import static org.junit.Assert.*; 2 | 3 | import java.math.BigInteger; 4 | 5 | import org.junit.Test; 6 | 7 | 8 | public class TailTest { 9 | 10 | @Test 11 | public void streamFactorial_should_work_with_1() { 12 | assertEquals(BigInteger.valueOf(1), Tail.streamFactorial(1)); 13 | } 14 | 15 | @Test 16 | public void streamFactorial_should_work_with_2() { 17 | assertEquals(BigInteger.valueOf(2), Tail.streamFactorial(2)); 18 | } 19 | 20 | @Test 21 | public void streamFactorial_should_work_with_3() { 22 | assertEquals(BigInteger.valueOf(6), Tail.streamFactorial(3)); 23 | } 24 | 25 | @Test 26 | public void stackFactorial_should_work_with_1() { 27 | assertEquals(BigInteger.valueOf(1), Tail.stackFactorial(1)); 28 | } 29 | 30 | @Test 31 | public void stackFactorial_should_work_with_2() { 32 | assertEquals(BigInteger.valueOf(2), Tail.stackFactorial(2)); 33 | } 34 | 35 | @Test 36 | public void stackFactorial_should_work_with_3() { 37 | assertEquals(BigInteger.valueOf(6), Tail.stackFactorial(3)); 38 | } 39 | 40 | @Test 41 | public void should_have_equal_factorials_of_555() { 42 | assertEquals(Tail.streamFactorial(555), Tail.stackFactorial(555)); 43 | } 44 | 45 | @Test 46 | public void should_have_equal_factorials_of_1234() { 47 | assertEquals(Tail.streamFactorial(1234), Tail.stackFactorial(1234)); 48 | } 49 | 50 | @Test(expected=StackOverflowError.class) 51 | public void should_throw_stack_overflow() { 52 | Tail.stackFactorial(56789); 53 | } 54 | 55 | @Test 56 | public void should_not_throw_stack_overflow() { 57 | Tail.streamFactorial(56789); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /Temporal.java: -------------------------------------------------------------------------------- 1 | import java.time.*; 2 | import static java.time.temporal.TemporalAdjusters.*; 3 | 4 | public class Temporal { 5 | 6 | public static void main(String...args) { 7 | 8 | LocalDate nextTuesday = LocalDate.now().with(next(DayOfWeek.TUESDAY)); 9 | 10 | System.out.println(nextTuesday); 11 | 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /ThreeTen.java: -------------------------------------------------------------------------------- 1 | import static java.lang.System.out; 2 | import java.time.LocalDate; 3 | import java.time.LocalDateTime; 4 | import java.time.Period; 5 | import java.time.temporal.ChronoUnit; 6 | 7 | // kudos to https://github.com/bbejeck 8 | public class ThreeTen { 9 | 10 | private static LocalDate today = LocalDate.of(2014, 3, 27); 11 | 12 | public static void main(String...args) { 13 | out.println("today=" + today); 14 | out.println("month=" + today.getMonth()); 15 | out.println("year=" + today.getYear()); 16 | 17 | LocalDate thirtyDaysFromNow = today.plusDays(30); 18 | out.println(thirtyDaysFromNow); 19 | 20 | out.println("today still=" + today); 21 | 22 | LocalDate nextMonth = today.plusMonths(1); 23 | out.println(nextMonth); 24 | 25 | LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS); 26 | out.println(nextWeek); 27 | 28 | LocalDate easter = LocalDate.of(2014, 4, 20); 29 | out.println("easter=" + easter); 30 | /* 31 | Period twoMonths = Period.ofMonths(2); 32 | out.println("2months=" + twoMonths); 33 | 34 | out.println("2months from now=" + today.plus(twoMonths)); 35 | //*/ 36 | /* 37 | Period timeUntilEaster = today.until(easter); 38 | out.println("timeUntilEaster=" + timeUntilEaster); 39 | out.println("timeUntilEaster=" + timeUntilEaster.getDays() + " days"); 40 | 41 | out.println("today - timeUntilEaster = " + today.minus(timeUntilEaster)); 42 | 43 | LocalDateTime ldt = today.atTime(6,45,0); 44 | out.println("time=" + ldt); 45 | //*/ 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Twoface.java: -------------------------------------------------------------------------------- 1 | interface Foo1 { 2 | default void foo() { 3 | System.out.println("foo"); 4 | } 5 | } 6 | interface Foo2 { 7 | default void foo() { 8 | System.out.println("foobar"); 9 | } 10 | } 11 | public class Twoface implements Foo1, Foo2 { 12 | //compilation error! 13 | 14 | public static void main(String...args) { 15 | new Twoface().foo(); 16 | } 17 | // public void foo() { Foo1.super.foo(); } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /Zones.java: -------------------------------------------------------------------------------- 1 | import java.time.*; 2 | import java.util.*; 3 | 4 | public class Zones { 5 | 6 | public static void main(String...args) { 7 | ZoneId zone = ZoneId.of("America/Denver"); 8 | System.out.println( zone ); 9 | System.out.println( ZoneId.systemDefault() ); 10 | 11 | Date date = new Date(); 12 | Instant now = date.toInstant(); 13 | System.out.println( now ); 14 | 15 | System.out.println( "Denver:" + LocalDateTime.ofInstant(now, zone) ); 16 | System.out.println( "Here:" + LocalDateTime.ofInstant(now, ZoneId.systemDefault()) ); 17 | 18 | System.out.println(ZoneId.getAvailableZoneIds() ); 19 | 20 | } 21 | } 22 | 23 | -------------------------------------------------------------------------------- /arr.js: -------------------------------------------------------------------------------- 1 | var icons = []; 2 | 3 | function loadIcons(iconNames) { 4 | for (var i = 0; i < iconNames.length; i++) { 5 | icons.push(iconNames[i]); 6 | print(icons); 7 | } 8 | } 9 | 10 | loadIcons(['test.png', 'test2.png']); 11 | 12 | print(icons.pop()); 13 | print(icons.pop()); 14 | -------------------------------------------------------------------------------- /concurrent.js: -------------------------------------------------------------------------------- 1 | var concurrent = new JavaImporter(java.util, java.util.concurrent); 2 | var Callable = Java.type("java.util.concurrent.Callable");
 3 | with (concurrent) { 4 | var executor = Executors.newCachedThreadPool(); 5 | var tasks = new LinkedHashSet(); 6 | for (var i=0; i < 200; i++) { 7 | var MyTask = Java.extend(Callable,{call: function() {print("task " + i)}}) 8 | var task = new MyTask(); 9 | tasks.add(task); 10 | executor.submit(task); 11 | } 12 | //executor.invokeAll(tasks); // oops 13 | } 14 | 15 | -------------------------------------------------------------------------------- /hello.js: -------------------------------------------------------------------------------- 1 | var hello = function() { 2 | print("Hello Nashorn!"); 3 | }; 4 | 5 | hello(); 6 | 7 | 8 | -------------------------------------------------------------------------------- /imports.js: -------------------------------------------------------------------------------- 1 | var imports = new JavaImporter(java.util, java.io, java.nio.file); 2 | with (imports) { 3 | var paths = new LinkedList(); 4 | print(paths instanceof LinkedList); // true 5 | paths.add(Paths.get("file1")); 6 | paths.add(Paths.get("file2")); 7 | paths.add(Paths.get("file3")); 8 | print(paths) 9 | 10 | for (var i=0; i < paths.size(); i++) 11 | Files.newOutputStream(paths.get(i)) 12 | .write("test\n".getBytes()); 13 | } 14 | 15 | -------------------------------------------------------------------------------- /jc8.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | /usr/lib/jvm/jdk1.8.0/bin/javac $1.java && /usr/lib/jvm/jdk1.8.0/bin/java $1 4 | 5 | -------------------------------------------------------------------------------- /jjs.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | /usr/lib/jvm/jdk1.8.0/bin/jjs $1 4 | 5 | 6 | -------------------------------------------------------------------------------- /paths.js: -------------------------------------------------------------------------------- 1 | var imports = new JavaImporter(java.util, java.io, java.nio.file); 2 | with (imports) { 3 | var paths = new LinkedList(); 4 | print(paths instanceof LinkedList); // true 5 | paths.add(Paths.get("file1")); 6 | paths.add(Paths.get("file2")); 7 | paths.add(Paths.get("file3")); 8 | print(paths) 9 | 10 | paths.forEach(function(path) { 11 | Files.newOutputStream(path) 12 | .write("test\n".getBytes());} 13 | ); 14 | } 15 | 16 | -------------------------------------------------------------------------------- /sum.js: -------------------------------------------------------------------------------- 1 | var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
 2 | 3 | print(typeof 1) 4 | print(typeof Array) 5 | print(data instanceof Array) //true 6 | 
var filtered = data.filter(function(i) {
 return i % 2 == 0;
});
print(filtered);

var sumOfFiltered = filtered.reduce(function(acc, next) {
 return acc + next;
}, 0); 7 | 
print(sumOfFiltered); 8 | -------------------------------------------------------------------------------- /sum2.js: -------------------------------------------------------------------------------- 1 | var data = [1, 3, 5, 7, 11] 2 | var sum = data.reduce(function(x, y) {return x + y}, 0) 3 | print(sum); 4 | 5 | --------------------------------------------------------------------------------