├── CourseInformation.pdf ├── Lesson 1 ├── Lambda Quick Start.adoc ├── README.adoc ├── exercices │ ├── LambdaCollectionExamples │ │ └── LambdaCollectionExamples │ │ │ ├── build.xml │ │ │ ├── manifest.mf │ │ │ ├── nbproject │ │ │ ├── build-impl.xml │ │ │ ├── genfiles.properties │ │ │ ├── private │ │ │ │ ├── config.properties │ │ │ │ ├── private.properties │ │ │ │ └── private.xml │ │ │ ├── project.properties │ │ │ └── project.xml │ │ │ └── src │ │ │ └── com │ │ │ └── example │ │ │ └── lambda │ │ │ ├── Gender.java │ │ │ ├── Main.java │ │ │ ├── Person.java │ │ │ ├── SearchCriteria.java │ │ │ ├── Test01ForEach.java │ │ │ ├── Test02Filter.java │ │ │ ├── Test03toList.java │ │ │ └── Test04Map.java │ ├── LambdaExamples01 │ │ └── LambdaExamples01 │ │ │ ├── build.xml │ │ │ ├── manifest.mf │ │ │ ├── nbproject │ │ │ ├── build-impl.xml │ │ │ ├── genfiles.properties │ │ │ ├── private │ │ │ │ ├── config.properties │ │ │ │ ├── private.properties │ │ │ │ └── private.xml │ │ │ ├── project.properties │ │ │ └── project.xml │ │ │ └── src │ │ │ └── com │ │ │ └── example │ │ │ └── lambda │ │ │ ├── #Untitled-1# │ │ │ ├── ComparatorTest.java │ │ │ ├── Gender.java │ │ │ ├── ListenerTest.java │ │ │ ├── Main.java │ │ │ ├── Person.java │ │ │ └── RunnableTest.java │ ├── LambdaFunctionExamples │ │ └── LambdaFunctionExamples │ │ │ ├── build.xml │ │ │ ├── manifest.mf │ │ │ ├── nbproject │ │ │ ├── build-impl.xml │ │ │ ├── genfiles.properties │ │ │ ├── private │ │ │ │ ├── config.properties │ │ │ │ ├── private.properties │ │ │ │ └── private.xml │ │ │ ├── project.properties │ │ │ └── project.xml │ │ │ └── src │ │ │ └── com │ │ │ └── example │ │ │ └── lambda │ │ │ ├── Gender.java │ │ │ ├── Main.java │ │ │ ├── NameTestNew.java │ │ │ ├── NameTestOld.java │ │ │ └── Person.java │ └── RoboCallExample │ │ └── RoboCallExample │ │ ├── build.xml │ │ ├── manifest.mf │ │ ├── nbproject │ │ ├── build-impl.xml │ │ ├── genfiles.properties │ │ ├── private │ │ │ ├── config.properties │ │ │ ├── private.properties │ │ │ └── private.xml │ │ ├── project.properties │ │ └── project.xml │ │ └── src │ │ └── com │ │ └── example │ │ └── lambda │ │ ├── Gender.java │ │ ├── Main.java │ │ ├── MyTest.java │ │ ├── Person.java │ │ ├── Predicate.java │ │ ├── RoboCallTest01.java │ │ ├── RoboCallTest02.java │ │ ├── RoboCallTest03.java │ │ ├── RoboCallTest04.java │ │ ├── RoboContactAnon.java │ │ ├── RoboContactLambda.java │ │ ├── RoboContactMethods.java │ │ └── RoboContactMethods2.java ├── homework │ ├── Lesson01-HW.pdf │ └── Lesson1.java └── slides │ ├── Lesson-1-1.pdf │ ├── Lesson-1-2.pdf │ ├── Lesson-1-3.pdf │ ├── Lesson-1-4.pdf │ ├── Lesson-1-5.pdf │ ├── Lesson-1-6.pdf │ └── Lesson-1-7.pdf ├── Lesson 2 ├── README.adoc ├── homework │ ├── Lesson02-HW.pdf │ ├── Lesson2.java │ └── hw.txt └── slides │ ├── Lesson-2-1.pdf │ ├── Lesson-2-2.pdf │ ├── Lesson-2-3.pdf │ ├── Lesson-2-4.pdf │ ├── Lesson-2-5.pdf │ ├── Lesson-2-6.pdf │ └── Lesson-2-7.pdf ├── Lesson 3 ├── README.adoc ├── homework │ ├── Lesson03-HW.pdf │ ├── Lesson3-HW.java │ ├── Levenshtein.java │ ├── RandomWords.java │ └── words.txt └── slides │ ├── Lesson-3-1.pdf │ ├── Lesson-3-2.pdf │ ├── Lesson-3-3.pdf │ ├── Lesson-3-4.pdf │ ├── Lesson-3-5.pdf │ ├── Lesson-3-6.pdf │ └── Lesson-3-7.pdf ├── README.adoc └── images └── route.png /CourseInformation.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/CourseInformation.pdf -------------------------------------------------------------------------------- /Lesson 1/Lambda Quick Start.adoc: -------------------------------------------------------------------------------- 1 | == Purpose 2 | 3 | This tutorial introduces the new lambda expressions included in Java Platform Standard Edition 8 (Java SE 8). 4 | 5 | == Introduction 6 | 7 | Lambda expressions are a new and important feature included in Java SE 8. They provide a clear and concise way to represent one method interface using an expression. Lambda expressions also improve the Collection libraries making it easier to iterate through, filter, and extract data from a Collection. In addition, new concurrency features improve performance in multicore environments. 8 | 9 | This Oracle by Example (OBE) provides an introduction to lambda expressions included in Java SE 8. An introduction to anonymous inner functions is provided, followed by a discussion of functional interfaces and the new lambda syntax. Then, examples of common usage patterns before and after lambda expressions are shown. 10 | 11 | The next section reviews a common search use case and how Java code can be improved with the inclusion of lambda expressions. In addition, some of the common functional interfaces, Predicate and Function, provided in java.util.function are shown in action. 12 | 13 | The OBE finishes up with a review of how the Java collection has been updated with lambda expressions. 14 | 15 | The source code for all examples is provided to you. 16 | 17 | == Hardware and Software Requirements 18 | 19 | The following is a list of hardware and software requirements: 20 | 21 | Java Development Kit (JDK 8) early access 22 | NetBeans 7.4 23 | Prerequisites 24 | 25 | To run the examples, you must have an early access version of JDK 8 and a copy of NetBeans 7.4 or later. Links can be found at the main Lambda site. For your convenience, here are the direct links. 26 | 27 | Java Development Kit 8 (JDK8) Early Access 28 | Recommended: Download the JDK 8 API Docs from the same page. 29 | NetBeans 7.4 or later. Version 7.4 of NetBeans includes support for JDK 8. 30 | Note: Builds are provided for all major operating systems. This OBE was developed using Linux Mint 13 (Ubuntu/Debian). 31 | 32 | Install JDK8 and NetBeans following the instructions provided with the downloads. Add the bin directories for Java and NetBeans to your PATH. 33 | 34 | NOTE: This OBE was last updated December 2013. 35 | 36 | == Background 37 | 38 | === Anonymous Inner Class 39 | 40 | In Java, anonymous inner classes provide a way to implement classes that may occur only once in an application. For example, in a standard Swing or JavaFX application a number of event handlers are required for keyboard and mouse events. Rather than writing a separate event-handling class for each event, you can write something like this. 41 | 42 | [source,java] 43 | ---- 44 | 16 JButton testButton = new JButton("Test Button"); 45 | 17 testButton.addActionListener(new ActionListener(){ 46 | 18 @Override public void actionPerformed(ActionEvent ae){ 47 | 19 System.out.println("Click Detected by Anon Class"); 48 | 20 } 49 | 21 }); 50 | ---- 51 | Otherwise, a separate class that implements ActionListener is required for each event. By creating the class in place, where it is needed, the code is a little easier to read. The code is not elegant, because quite a bit of code is required just to define one method. 52 | 53 | == Functional Interfaces 54 | 55 | The code that defines the ActionListener interface, looks something like this: 56 | 57 | [source,java] 58 | ---- 59 | 1 package java.awt.event; 60 | 2 import java.util.EventListener; 61 | 3 62 | 4 public interface ActionListener extends EventListener { 63 | 5 64 | 6 public void actionPerformed(ActionEvent e); 65 | 7 66 | 8 } 67 | ---- 68 | 69 | The ActionListener example is an interface with only one method. With Java SE 8, an interface that follows this pattern is known as a "functional interface." 70 | 71 | NOTE: This type of interface, was previously known as a Single Abstract Method type (SAM). 72 | 73 | Using functional interfaces with anonymous inner classes are a common pattern in Java. In addition to the EventListener classes, interfaces like Runnable and Comparator are used in a similar manner. Therefore, functional interfaces are leveraged for use with lambda expressions. 74 | 75 | == Lambda Expression Syntax 76 | 77 | Lambda expressions address the bulkiness of anonymous inner classes by converting five lines of code into a single statement. This simple horizontal solution solves the "vertical problem" presented by inner classes. 78 | 79 | A lambda expression is composed of three parts. 80 | 81 | |=== 82 | |Argument List| Arrow| Token Body 83 | |(int x, int y) |->| x + y 84 | |=== 85 | 86 | The body can be either a single expression or a statement block. In the expression form, the body is simply evaluated and returned. In the block form, the body is evaluated like a method body and a return statement returns control to the caller of the anonymous method. The break and continue keywords are illegal at the top level, but are permitted within loops. If the body produces a result, every control path must return something or throw an exception. 87 | 88 | Take a look at these examples: 89 | 90 | [source,java] 91 | ---- 92 | (int x, int y) -> x + y 93 | 94 | () -> 42 95 | 96 | (String s) -> { System.out.println(s); } 97 | ---- 98 | 99 | The first expression takes two integer arguments, named x and y, and uses the expression form to return x+y. The second expression takes no arguments and uses the expression form to return an integer 42. The third expression takes a string and uses the block form to print the string to the console, and returns nothing. 100 | 101 | With the basics of syntax covered, let's look at some examples. 102 | 103 | 104 | == Lambda Examples 105 | Here are some common use cases using the previously covered examples. 106 | 107 | === Runnable Lambda 108 | 109 | Here is how you write a Runnable using lambdas. 110 | [source,java] 111 | ---- 112 | 6 public class RunnableTest { 113 | 7 public static void main(String[] args) { 114 | 8 115 | 9 System.out.println("=== RunnableTest ==="); 116 | 10 117 | 11 // Anonymous Runnable 118 | 12 Runnable r1 = new Runnable(){ 119 | 13 120 | 14 @Override 121 | 15 public void run(){ 122 | 16 System.out.println("Hello world one!"); 123 | 17 } 124 | 18 }; 125 | 19 126 | 20 // Lambda Runnable 127 | 21 Runnable r2 = () -> System.out.println("Hello world two!"); 128 | 22 129 | 23 // Run em! 130 | 24 r1.run(); 131 | 25 r2.run(); 132 | 26 133 | 27 } 134 | 28 } 135 | ---- 136 | In both cases, notice that no parameter is passed and is returned. The Runnable lambda expression, which uses the block format, converts five lines of code into one statement. 137 | 138 | === Comparator Lambda 139 | 140 | In Java, the Comparator class is used for sorting collections. In the following example, an ArrayList consisting of Person objects is sorted based on surName. The following are the fields included in the Person class. 141 | 142 | ---- 143 | 9 public class Person { 144 | 10 private String givenName; 145 | 11 private String surName; 146 | 12 private int age; 147 | 13 private Gender gender; 148 | 14 private String eMail; 149 | 15 private String phone; 150 | 16 private String address; 151 | 17 152 | ---- 153 | 154 | The following code applies a Comparator by using an anonymous inner class and a couple lambda expressions. 155 | 156 | [source,java] 157 | ---- 158 | 10 public class ComparatorTest { 159 | 11 160 | 12 public static void main(String[] args) { 161 | 13 162 | 14 List personList = Person.createShortList(); 163 | 15 164 | 16 // Sort with Inner Class 165 | 17 Collections.sort(personList, new Comparator(){ 166 | 18 public int compare(Person p1, Person p2){ 167 | 19 return p1.getSurName().compareTo(p2.getSurName()); 168 | 20 } 169 | 21 }); 170 | 22 171 | 23 System.out.println("=== Sorted Asc SurName ==="); 172 | 24 for(Person p:personList){ 173 | 25 p.printName(); 174 | 26 } 175 | 27 176 | 28 // Use Lambda instead 177 | 29 178 | 30 // Print Asc 179 | 31 System.out.println("=== Sorted Asc SurName ==="); 180 | 32 Collections.sort(personList, (Person p1, Person p2) -> p1.getSurName().compareTo(p2.getSurName())); 181 | 33 182 | 34 for(Person p:personList){ 183 | 35 p.printName(); 184 | 36 } 185 | 37 186 | 38 // Print Desc 187 | 39 System.out.println("=== Sorted Desc SurName ==="); 188 | 40 Collections.sort(personList, (p1, p2) -> p2.getSurName().compareTo(p1.getSurName())); 189 | 41 190 | 42 for(Person p:personList){ 191 | 43 p.printName(); 192 | 44 } 193 | 45 194 | 46 } 195 | 47 } 196 | ---- 197 | 198 | Lines 17 - 21 are easily replaced by the lambda expression on line 32. Notice that the first lambda expression declares the parameter type passed to the expression. However, as you can see from the second expression, this is optional. Lambda supports "target typing" which infers the object type from the context in which it is used. Because we are assigning the result to a Comparator defined with a generic, the compiler can infer that the two parameters are of the Person type. 199 | 200 | === Listener Lambda 201 | 202 | Finally, let's revisit the ActionListener example. 203 | 204 | [source,java] 205 | ---- 206 | 13 public class ListenerTest { 207 | 14 public static void main(String[] args) { 208 | 15 209 | 16 JButton testButton = new JButton("Test Button"); 210 | 17 testButton.addActionListener(new ActionListener(){ 211 | 18 @Override public void actionPerformed(ActionEvent ae){ 212 | 19 System.out.println("Click Detected by Anon Class"); 213 | 20 } 214 | 21 }); 215 | 22 216 | 23 testButton.addActionListener(e -> System.out.println("Click Detected by Lambda Listner")); 217 | 24 218 | 25 // Swing stuff 219 | 26 JFrame frame = new JFrame("Listener Test"); 220 | 27 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 221 | 28 frame.add(testButton, BorderLayout.CENTER); 222 | 29 frame.pack(); 223 | 30 frame.setVisible(true); 224 | 31 225 | 32 } 226 | 33 } 227 | ---- 228 | 229 | Notice that the lambda expression is passed as a parameter. Target typing is used in a number of contexts including the following: 230 | 231 | Variable declarations 232 | Assignments 233 | Return statements 234 | Array initializers 235 | Method or constructor arguments 236 | Lambda expression bodies 237 | Conditional expressions ?: 238 | Cast expressions 239 | 240 | === Improving Code with Lambda Expressions 241 | 242 | This section builds upon the previous examples to show you how lambda expressions can improve your code. Lambdas should provide a means to better support the Don't Repeat Yourself (DRY) principle and make your code simpler and more readable. 243 | 244 | ==== A Common Query Use Case 245 | 246 | A common use case for programs is to search through a collection of data to find items that match a specific criteria. In the excellent "Jump-Starting Lambda" presentation at JavaOne 2012, Stuart Marks and Mike Duigou walk though just such a use case. Given a list of people, various criteria are used to make robo calls (automated phone calls) to matching persons. This tutorial follows that basic premise with slight variations. 247 | 248 | In this example, our message needs to get out to three different groups in the United States: 249 | 250 | Drivers: Persons over the age of 16 251 | Draftees: Male persons between the ages of 18 and 25 252 | Pilots (specifically commercial pilots): Persons between the ages of 23 and 65 253 | The actual robot that does all this work has not yet arrived at our place of business. Instead of calling, mailing or emailing, a message is printed to the console. The message contains a person's name, age, and information specific to the target medium (for example, email address when emailing or phone number when calling). 254 | 255 | ==== Person Class 256 | 257 | Each person in the test list is defined by using the Person class with the following properties: 258 | 259 | [source,java] 260 | ---- 261 | 10 public class Person { 262 | 11 private String givenName; 263 | 12 private String surName; 264 | 13 private int age; 265 | 14 private Gender gender; 266 | 15 private String eMail; 267 | 16 private String phone; 268 | 17 private String address; 269 | 18 270 | ---- 271 | 272 | The Person class uses a Builder to create new objects. A sample list of people is created with the createShortList method. Here is a short code fragment of that method. Note: All source code for this tutorial is included in a NetBeans project that is linked at the end of this section. 273 | 274 | [source,java] 275 | ---- 276 | 128 public static List createShortList(){ 277 | 129 List people = new ArrayList<>(); 278 | 130 279 | 131 people.add( 280 | 132 new Person.Builder() 281 | 133 .givenName("Bob") 282 | 134 .surName("Baker") 283 | 135 .age(21) 284 | 136 .gender(Gender.MALE) 285 | 137 .email("bob.baker@example.com") 286 | 138 .phoneNumber("201-121-4678") 287 | 139 .address("44 4th St, Smallville, KS 12333") 288 | 140 .build() 289 | 141 ); 290 | 142 291 | 143 people.add( 292 | 144 new Person.Builder() 293 | 145 .givenName("Jane") 294 | 146 .surName("Doe") 295 | 147 .age(25) 296 | 148 .gender(Gender.FEMALE) 297 | 149 .email("jane.doe@example.com") 298 | 150 .phoneNumber("202-123-4678") 299 | 151 .address("33 3rd St, Smallville, KS 12333") 300 | 152 .build() 301 | 153 ); 302 | 154 303 | 155 people.add( 304 | 156 new Person.Builder() 305 | 157 .givenName("John") 306 | 158 .surName("Doe") 307 | 159 .age(25) 308 | 160 .gender(Gender.MALE) 309 | 161 .email("john.doe@example.com") 310 | 162 .phoneNumber("202-123-4678") 311 | 163 .address("33 3rd St, Smallville, KS 12333") 312 | 164 .build() 313 | 165 ); 314 | 166 315 | ---- 316 | 317 | === A First Attempt 318 | 319 | With a Person class and search criteria defined, you can write a RoboContact class. One possible solution defines a method for each use case: 320 | 321 | [source,java] 322 | .RoboContactsMethods.java 323 | ---- 324 | 1 package com.example.lambda; 325 | 2 326 | 3 import java.util.List; 327 | 4 328 | 5 /** 329 | 6 * 330 | 7 * @author MikeW 331 | 8 */ 332 | 9 public class RoboContactMethods { 333 | 10 334 | 11 public void callDrivers(List pl){ 335 | 12 for(Person p:pl){ 336 | 13 if (p.getAge() >= 16){ 337 | 14 roboCall(p); 338 | 15 } 339 | 16 } 340 | 17 } 341 | 18 342 | 19 public void emailDraftees(List pl){ 343 | 20 for(Person p:pl){ 344 | 21 if (p.getAge() >= 18 && p.getAge() <= 25 && p.getGender() == Gender.MALE){ 345 | 22 roboEmail(p); 346 | 23 } 347 | 24 } 348 | 25 } 349 | 26 350 | 27 public void mailPilots(List pl){ 351 | 28 for(Person p:pl){ 352 | 29 if (p.getAge() >= 23 && p.getAge() <= 65){ 353 | 30 roboMail(p); 354 | 31 } 355 | 32 } 356 | 33 } 357 | 34 358 | 35 359 | 36 public void roboCall(Person p){ 360 | 37 System.out.println("Calling " + p.getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p.getPhone()); 361 | 38 } 362 | 39 363 | 40 public void roboEmail(Person p){ 364 | 41 System.out.println("EMailing " + p.getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p.getEmail()); 365 | 42 } 366 | 43 367 | 44 public void roboMail(Person p){ 368 | 45 System.out.println("Mailing " + p.getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p.getAddress()); 369 | 46 } 370 | 47 371 | 48 } 372 | ---- 373 | 374 | As you can see from the names (callDrivers, emailDraftees, and mailPilots) the methods describe the kind of behavior that is taking place. The search criteria is clearly conveyed and an appropriate call is made to each robo action. However, this design has some negatives aspects: 375 | 376 | The DRY principle is not followed. 377 | Each method repeats a looping mechanism. 378 | The selection criteria must be rewritten for each method 379 | A large number of methods are required to implement each use case. 380 | The code is inflexible. If the search criteria changed, it would require a number of code changes for an update. Thus, the code is not very maintainable. 381 | Refactor the Methods 382 | 383 | How can the class be fixed? The search criteria is a good place to start. If test conditions are isolated in separate methods, that would be an improvement. 384 | 385 | [source,java] 386 | .RoboContactMethods2.java 387 | ---- 388 | 1 package com.example.lambda; 389 | 2 390 | 3 import java.util.List; 391 | 4 392 | 5 /** 393 | 6 * 394 | 7 * @author MikeW 395 | 8 */ 396 | 9 public class RoboContactMethods2 { 397 | 10 398 | 11 public void callDrivers(List pl){ 399 | 12 for(Person p:pl){ 400 | 13 if (isDriver(p)){ 401 | 14 roboCall(p); 402 | 15 } 403 | 16 } 404 | 17 } 405 | 18 406 | 19 public void emailDraftees(List pl){ 407 | 20 for(Person p:pl){ 408 | 21 if (isDraftee(p)){ 409 | 22 roboEmail(p); 410 | 23 } 411 | 24 } 412 | 25 } 413 | 26 414 | 27 public void mailPilots(List pl){ 415 | 28 for(Person p:pl){ 416 | 29 if (isPilot(p)){ 417 | 30 roboMail(p); 418 | 31 } 419 | 32 } 420 | 33 } 421 | 34 422 | 35 public boolean isDriver(Person p){ 423 | 36 return p.getAge() >= 16; 424 | 37 } 425 | 38 426 | 39 public boolean isDraftee(Person p){ 427 | 40 return p.getAge() >= 18 && p.getAge() <= 25 && p.getGender() == Gender.MALE; 428 | 41 } 429 | 42 430 | 43 public boolean isPilot(Person p){ 431 | 44 return p.getAge() >= 23 && p.getAge() <= 65; 432 | 45 } 433 | 46 434 | 47 public void roboCall(Person p){ 435 | 48 System.out.println("Calling " + p.getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p.getPhone()); 436 | 49 } 437 | 50 438 | 51 public void roboEmail(Person p){ 439 | 52 System.out.println("EMailing " + p.getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p.getEmail()); 440 | 53 } 441 | 54 442 | 55 public void roboMail(Person p){ 443 | 56 System.out.println("Mailing " + p.getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p.getAddress()); 444 | 57 } 445 | 58 446 | 59 } 447 | ---- 448 | 449 | The search criteria are encapsulated in a method, an improvement over the previous example. The test conditions can be reused and changes flow back throughout the class. However there is still a lot of repeated code and a separate method is still required for each use case. Is there a better way to pass the search criteria to the methods? 450 | 451 | == Anonymous Classes 452 | 453 | Before lambda expressions, anonymous inner classes were an option. For example, an interface (MyTest.java) written with one test method that returns a boolean (a functional interface) is a possible solution. The search criteria could be passed when the method is called. The interface looks like this: 454 | 455 | [source,java] 456 | ---- 457 | 6 public interface MyTest { 458 | 7 public boolean test(T t); 459 | 8 } 460 | ---- 461 | 462 | The updated robot class looks like this: 463 | 464 | [source,java] 465 | .RoboContactsAnon.java 466 | ---- 467 | 9 public class RoboContactAnon { 468 | 10 469 | 11 public void phoneContacts(List pl, MyTest aTest){ 470 | 12 for(Person p:pl){ 471 | 13 if (aTest.test(p)){ 472 | 14 roboCall(p); 473 | 15 } 474 | 16 } 475 | 17 } 476 | 18 477 | 19 public void emailContacts(List pl, MyTest aTest){ 478 | 20 for(Person p:pl){ 479 | 21 if (aTest.test(p)){ 480 | 22 roboEmail(p); 481 | 23 } 482 | 24 } 483 | 25 } 484 | 26 485 | 27 public void mailContacts(List pl, MyTest aTest){ 486 | 28 for(Person p:pl){ 487 | 29 if (aTest.test(p)){ 488 | 30 roboMail(p); 489 | 31 } 490 | 32 } 491 | 33 } 492 | 34 493 | 35 public void roboCall(Person p){ 494 | 36 System.out.println("Calling " + p.getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p.getPhone()); 495 | 37 } 496 | 38 497 | 39 public void roboEmail(Person p){ 498 | 40 System.out.println("EMailing " + p.getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p.getEmail()); 499 | 41 } 500 | 42 501 | 43 public void roboMail(Person p){ 502 | 44 System.out.println("Mailing " + p.getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p.getAddress()); 503 | 45 } 504 | 46 505 | 47 } 506 | ---- 507 | That is definitely another improvement, because only three methods are needed to perform robotic operations. However, there is a slight problem with ugliness when the methods are called. Check out the test class used for this class: 508 | 509 | [source,java] 510 | .RoboCallTest03.java 511 | ---- 512 | 1 package com.example.lambda; 513 | 2 514 | 3 import java.util.List; 515 | 4 516 | 5 /** 517 | 6 * @author MikeW 518 | 7 */ 519 | 8 public class RoboCallTest03 { 520 | 9 521 | 10 public static void main(String[] args) { 522 | 11 523 | 12 List pl = Person.createShortList(); 524 | 13 RoboContactAnon robo = new RoboContactAnon(); 525 | 14 526 | 15 System.out.println("\n==== Test 03 ===="); 527 | 16 System.out.println("\n=== Calling all Drivers ==="); 528 | 17 robo.phoneContacts(pl, 529 | 18 new MyTest(){ 530 | 19 @Override 531 | 20 public boolean test(Person p){ 532 | 21 return p.getAge() >=16; 533 | 22 } 534 | 23 } 535 | 24 ); 536 | 25 537 | 26 System.out.println("\n=== Emailing all Draftees ==="); 538 | 27 robo.emailContacts(pl, 539 | 28 new MyTest(){ 540 | 29 @Override 541 | 30 public boolean test(Person p){ 542 | 31 return p.getAge() >= 18 && p.getAge() <= 25 && p.getGender() == Gender.MALE; 543 | 32 } 544 | 33 } 545 | 34 ); 546 | 35 547 | 36 548 | 37 System.out.println("\n=== Mail all Pilots ==="); 549 | 38 robo.mailContacts(pl, 550 | 39 new MyTest(){ 551 | 40 @Override 552 | 41 public boolean test(Person p){ 553 | 42 return p.getAge() >= 23 && p.getAge() <= 65; 554 | 43 } 555 | 44 } 556 | 45 ); 557 | 46 558 | 47 559 | 48 } 560 | 49 } 561 | ---- 562 | This is a great example of the "vertical" problem in practice. This code is a little difficult to read. In addition, we have to write custom search criteria for each use case. 563 | 564 | === Lambda Expressions Get it Just Right 565 | 566 | Lambda expressions solve all the problems encountered so far. But first a little housekeeping. 567 | 568 | java.util.function 569 | 570 | In the previous example, the MyTest functional interface passed anonymous classes to methods. However, writing that interface was not necessary. Java SE 8 provides the java.util.function package with a number of standard functional interfaces. In this case, the Predicate interface meets our needs. 571 | 572 | [source,java] 573 | ---- 574 | 3 public interface Predicate { 575 | 4 public boolean test(T t); 576 | 5 } 577 | ---- 578 | 579 | The test method takes a generic class and returns a boolean result. This is just what is needed to make selections. Here is the final version of the robot class. 580 | 581 | [source,java] 582 | .RoboContactsLambda.java 583 | ---- 584 | 1 package com.example.lambda; 585 | 2 586 | 3 import java.util.List; 587 | 4 import java.util.function.Predicate; 588 | 5 589 | 6 /** 590 | 7 * 591 | 8 * @author MikeW 592 | 9 */ 593 | 10 public class RoboContactLambda { 594 | 11 public void phoneContacts(List pl, Predicate pred){ 595 | 12 for(Person p:pl){ 596 | 13 if (pred.test(p)){ 597 | 14 roboCall(p); 598 | 15 } 599 | 16 } 600 | 17 } 601 | 18 602 | 19 public void emailContacts(List pl, Predicate pred){ 603 | 20 for(Person p:pl){ 604 | 21 if (pred.test(p)){ 605 | 22 roboEmail(p); 606 | 23 } 607 | 24 } 608 | 25 } 609 | 26 610 | 27 public void mailContacts(List pl, Predicate pred){ 611 | 28 for(Person p:pl){ 612 | 29 if (pred.test(p)){ 613 | 30 roboMail(p); 614 | 31 } 615 | 32 } 616 | 33 } 617 | 34 618 | 35 public void roboCall(Person p){ 619 | 36 System.out.println("Calling " + p.getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p.getPhone()); 620 | 37 } 621 | 38 622 | 39 public void roboEmail(Person p){ 623 | 40 System.out.println("EMailing " + p.getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p.getEmail()); 624 | 41 } 625 | 42 626 | 43 public void roboMail(Person p){ 627 | 44 System.out.println("Mailing " + p.getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p.getAddress()); 628 | 45 } 629 | 46 630 | 47 } 631 | ---- 632 | With this approach only three methods are needed, one for each contact method. The lambda expression passed to the method selects the Person instances that meet the test conditions. 633 | 634 | Vertical Problem Solved 635 | 636 | Lambda expressions solve the vertical problem and allow the easy reuse of any expression. Take a look at the new test class updated for lambda expressions. 637 | 638 | [source,java] 639 | .RoboCallTest04.java 640 | ---- 641 | 1 package com.example.lambda; 642 | 2 643 | 3 import java.util.List; 644 | 4 import java.util.function.Predicate; 645 | 5 646 | 6 /** 647 | 7 * 648 | 8 * @author MikeW 649 | 9 */ 650 | 10 public class RoboCallTest04 { 651 | 11 652 | 12 public static void main(String[] args){ 653 | 13 654 | 14 List pl = Person.createShortList(); 655 | 15 RoboContactLambda robo = new RoboContactLambda(); 656 | 16 657 | 17 // Predicates 658 | 18 Predicate allDrivers = p -> p.getAge() >= 16; 659 | 19 Predicate allDraftees = p -> p.getAge() >= 18 && p.getAge() <= 25 && p.getGender() == Gender.MALE; 660 | 20 Predicate allPilots = p -> p.getAge() >= 23 && p.getAge() <= 65; 661 | 21 662 | 22 System.out.println("\n==== Test 04 ===="); 663 | 23 System.out.println("\n=== Calling all Drivers ==="); 664 | 24 robo.phoneContacts(pl, allDrivers); 665 | 25 666 | 26 System.out.println("\n=== Emailing all Draftees ==="); 667 | 27 robo.emailContacts(pl, allDraftees); 668 | 28 669 | 29 System.out.println("\n=== Mail all Pilots ==="); 670 | 30 robo.mailContacts(pl, allPilots); 671 | 31 672 | 32 // Mix and match becomes easy 673 | 33 System.out.println("\n=== Mail all Draftees ==="); 674 | 34 robo.mailContacts(pl, allDraftees); 675 | 35 676 | 36 System.out.println("\n=== Call all Pilots ==="); 677 | 37 robo.phoneContacts(pl, allPilots); 678 | 38 679 | 39 } 680 | 40 } 681 | ---- 682 | 683 | Notice that a Predicate is set up for each group: allDrivers, allDraftees, and allPilots. You can pass any of these Predicate interfaces to the contact methods. The code is compact and easy to read, and it is not repetitive. 684 | 685 | The java.util.function Package 686 | The java.util.function Package 687 | 688 | Of course, Predicate is not the only functional interface provided with Java SE 8. A number of standard interfaces are designed as a starter set for developers. 689 | 690 | . Predicate: A property of the object passed as argument 691 | . Consumer: An action to be performed with the object passed as argument 692 | . Function: Transform a T to a U 693 | . Supplier: Provide an instance of a T (such as a factory) 694 | . UnaryOperator: A unary operator from T -> T 695 | . BinaryOperator: A binary operator from (T, T) -> T 696 | . In addition, many of these interfaces also have primitive versions. This should give you a great starting point for your lambda expressions. 697 | 698 | == Eastern Style Names and Method References 699 | 700 | When working on the previous example, I decided it would be nice to have a flexible printing system for the Person class. One feature requirement is to display names in both a western style and an eastern style. In the West, names are displayed with the given name first and the surname second. In many eastern cultures, names are displayed with the surname first and the given name second. 701 | 702 | === An Old Style Example 703 | 704 | Here is an example of how to implement a Person printing class without lambda support. 705 | 706 | [source,java] 707 | .Person.java 708 | ---- 709 | 128 public void printWesternName(){ 710 | 129 711 | 130 System.out.println("\nName: " + this.getGivenName() + " " + this.getSurName() + "\n" + 712 | 131 "Age: " + this.getAge() + " " + "Gender: " + this.getGender() + "\n" + 713 | 132 "EMail: " + this.getEmail() + "\n" + 714 | 133 "Phone: " + this.getPhone() + "\n" + 715 | 134 "Address: " + this.getAddress()); 716 | 135 } 717 | 136 718 | 137 719 | 138 720 | 139 public void printEasternName(){ 721 | 140 722 | 141 System.out.println("\nName: " + this.getSurName() + " " + this.getGivenName() + "\n" + 723 | 142 "Age: " + this.getAge() + " " + "Gender: " + this.getGender() + "\n" + 724 | 143 "EMail: " + this.getEmail() + "\n" + 725 | 144 "Phone: " + this.getPhone() + "\n" + 726 | 145 "Address: " + this.getAddress()); 727 | 146 } 728 | ---- 729 | 730 | A method exists for each style that prints out a person. 731 | 732 | == The Function Interface 733 | 734 | The Function interface is useful for this problem. It has only one method apply with the following signature: 735 | 736 | [source,java] 737 | ---- 738 | public R apply(T t){ } 739 | ---- 740 | 741 | It takes a generic class T and returns a generic class R. For this example, pass the Person class and return a String. A more flexible print method for person could be written like this: 742 | 743 | [source,java] 744 | .Person.java 745 | ---- 746 | 123 public String printCustom(Function f){ 747 | 124 return f.apply(this); 748 | 125 } 749 | 126 750 | ---- 751 | 752 | That is quite a bit simpler. A Function is passed to the method and a string returned. The apply method processes a lambda expression which determines what Person information is returned. 753 | 754 | How are the Functions defined? Here is the test code that calls the previous method. 755 | 756 | [source,java] 757 | .NameTestNew.java 758 | ---- 759 | 9 public class NameTestNew { 760 | 10 761 | 11 public static void main(String[] args) { 762 | 12 763 | 13 System.out.println("\n==== NameTestNew02 ==="); 764 | 14 765 | 15 List list1 = Person.createShortList(); 766 | 16 767 | 17 // Print Custom First Name and e-mail 768 | 18 System.out.println("===Custom List==="); 769 | 19 for (Person person:list1){ 770 | 20 System.out.println( 771 | 21 person.printCustom(p -> "Name: " + p.getGivenName() + " EMail: " + p.getEmail()) 772 | 22 ); 773 | 23 } 774 | 24 775 | 25 776 | 26 // Define Western and Eastern Lambdas 777 | 27 778 | 28 Function westernStyle = p -> { 779 | 29 return "\nName: " + p.getGivenName() + " " + p.getSurName() + "\n" + 780 | 30 "Age: " + p.getAge() + " " + "Gender: " + p.getGender() + "\n" + 781 | 31 "EMail: " + p.getEmail() + "\n" + 782 | 32 "Phone: " + p.getPhone() + "\n" + 783 | 33 "Address: " + p.getAddress(); 784 | 34 }; 785 | 35 786 | 36 Function easternStyle = p -> "\nName: " + p.getSurName() + " " 787 | 37 + p.getGivenName() + "\n" + "Age: " + p.getAge() + " " + 788 | 38 "Gender: " + p.getGender() + "\n" + 789 | 39 "EMail: " + p.getEmail() + "\n" + 790 | 40 "Phone: " + p.getPhone() + "\n" + 791 | 41 "Address: " + p.getAddress(); 792 | 42 793 | 43 // Print Western List 794 | 44 System.out.println("\n===Western List==="); 795 | 45 for (Person person:list1){ 796 | 46 System.out.println( 797 | 47 person.printCustom(westernStyle) 798 | 48 ); 799 | 49 } 800 | 50 801 | 51 // Print Eastern List 802 | 52 System.out.println("\n===Eastern List==="); 803 | 53 for (Person person:list1){ 804 | 54 System.out.println( 805 | 55 person.printCustom(easternStyle) 806 | 56 ); 807 | 57 } 808 | 58 809 | 59 810 | 60 } 811 | 61 } 812 | ---- 813 | 814 | The first loop just prints given name and the email address. But any valid expression could be passed to the printCustom method. Eastern and western print styles are defined with lambda expressions and stored in a variable. The variables are then passed to the final two loops. The lambda expressions could very easily be incorporated into a Map to make their reuse much easier. The lambda expression provides a great deal of flexibility. 815 | 816 | ==== Sample Output 817 | 818 | Here is some sample output from the program. 819 | 820 | [source,java] 821 | ---- 822 | ==== NameTestNew02 === 823 | ===Custom List=== 824 | Name: Bob EMail: bob.baker@example.com 825 | Name: Jane EMail: jane.doe@example.com 826 | Name: John EMail: john.doe@example.com 827 | Name: James EMail: james.johnson@example.com 828 | Name: Joe EMail: joebob.bailey@example.com 829 | Name: Phil EMail: phil.smith@examp;e.com 830 | Name: Betty EMail: betty.jones@example.com 831 | 832 | ===Western List=== 833 | 834 | Name: Bob Baker 835 | Age: 21 Gender: MALE 836 | EMail: bob.baker@example.com 837 | Phone: 201-121-4678 838 | Address: 44 4th St, Smallville, KS 12333 839 | 840 | Name: Jane Doe 841 | Age: 25 Gender: FEMALE 842 | EMail: jane.doe@example.com 843 | Phone: 202-123-4678 844 | Address: 33 3rd St, Smallville, KS 12333 845 | 846 | Name: John Doe 847 | Age: 25 Gender: MALE 848 | EMail: john.doe@example.com 849 | Phone: 202-123-4678 850 | Address: 33 3rd St, Smallville, KS 12333 851 | 852 | Name: James Johnson 853 | Age: 45 Gender: MALE 854 | EMail: james.johnson@example.com 855 | Phone: 333-456-1233 856 | Address: 201 2nd St, New York, NY 12111 857 | 858 | Name: Joe Bailey 859 | Age: 67 Gender: MALE 860 | EMail: joebob.bailey@example.com 861 | Phone: 112-111-1111 862 | Address: 111 1st St, Town, CA 11111 863 | 864 | Name: Phil Smith 865 | Age: 55 Gender: MALE 866 | EMail: phil.smith@examp;e.com 867 | Phone: 222-33-1234 868 | Address: 22 2nd St, New Park, CO 222333 869 | 870 | Name: Betty Jones 871 | Age: 85 Gender: FEMALE 872 | EMail: betty.jones@example.com 873 | Phone: 211-33-1234 874 | Address: 22 4th St, New Park, CO 222333 875 | 876 | ===Eastern List=== 877 | 878 | Name: Baker Bob 879 | Age: 21 Gender: MALE 880 | EMail: bob.baker@example.com 881 | Phone: 201-121-4678 882 | Address: 44 4th St, Smallville, KS 12333 883 | 884 | Name: Doe Jane 885 | Age: 25 Gender: FEMALE 886 | EMail: jane.doe@example.com 887 | Phone: 202-123-4678 888 | Address: 33 3rd St, Smallville, KS 12333 889 | 890 | Name: Doe John 891 | Age: 25 Gender: MALE 892 | EMail: john.doe@example.com 893 | Phone: 202-123-4678 894 | Address: 33 3rd St, Smallville, KS 12333 895 | 896 | Name: Johnson James 897 | Age: 45 Gender: MALE 898 | EMail: james.johnson@example.com 899 | Phone: 333-456-1233 900 | Address: 201 2nd St, New York, NY 12111 901 | 902 | Name: Bailey Joe 903 | Age: 67 Gender: MALE 904 | EMail: joebob.bailey@example.com 905 | Phone: 112-111-1111 906 | Address: 111 1st St, Town, CA 11111 907 | 908 | Name: Smith Phil 909 | Age: 55 Gender: MALE 910 | EMail: phil.smith@examp;e.com 911 | Phone: 222-33-1234 912 | Address: 22 2nd St, New Park, CO 222333 913 | 914 | Name: Jones Betty 915 | Age: 85 Gender: FEMALE 916 | EMail: betty.jones@example.com 917 | Phone: 211-33-1234 918 | Address: 22 4th St, New Park, CO 222333 919 | ---- 920 | 921 | 922 | === Lambda Expressions and Collections 923 | The previous section introduced the Function interface and finished up examples of basic lambda expression syntax. This section reviews how lambda expressions improve the Collection classes. 924 | 925 | ==== Lambda Expressions and Collections 926 | 927 | In the examples created so far, the collections classes were used quite a bit. However, a number of new lambda expression features change the way collections are used. This section introduces a few of these new features. 928 | 929 | ==== Class Additions 930 | 931 | The drivers, pilots, and draftees search criteria have been encapsulated in the SearchCriteria class. 932 | 933 | [source,java] 934 | .SearchCriteria.java 935 | ---- 936 | 1 package com.example.lambda; 937 | 2 938 | 3 import java.util.HashMap; 939 | 4 import java.util.Map; 940 | 5 import java.util.function.Predicate; 941 | 6 942 | 7 /** 943 | 8 * 944 | 9 * @author MikeW 945 | 10 */ 946 | 11 public class SearchCriteria { 947 | 12 948 | 13 private final Map> searchMap = new HashMap<>(); 949 | 14 950 | 15 private SearchCriteria() { 951 | 16 super(); 952 | 17 initSearchMap(); 953 | 18 } 954 | 19 955 | 20 private void initSearchMap() { 956 | 21 Predicate allDrivers = p -> p.getAge() >= 16; 957 | 22 Predicate allDraftees = p -> p.getAge() >= 18 && p.getAge() <= 25 && p.getGender() == Gender.MALE; 958 | 23 Predicate allPilots = p -> p.getAge() >= 23 && p.getAge() <= 65; 959 | 24 960 | 25 searchMap.put("allDrivers", allDrivers); 961 | 26 searchMap.put("allDraftees", allDraftees); 962 | 27 searchMap.put("allPilots", allPilots); 963 | 28 964 | 29 } 965 | 30 966 | 31 public Predicate getCriteria(String PredicateName) { 967 | 32 Predicate target; 968 | 33 969 | 34 target = searchMap.get(PredicateName); 970 | 35 971 | 36 if (target == null) { 972 | 37 973 | 38 System.out.println("Search Criteria not found... "); 974 | 39 System.exit(1); 975 | 40 976 | 41 } 977 | 42 978 | 43 return target; 979 | 44 980 | 45 } 981 | 46 982 | 47 public static SearchCriteria getInstance() { 983 | 48 return new SearchCriteria(); 984 | 49 } 985 | 50 } 986 | ---- 987 | 988 | The Predicate based search criteria are stored in this class and available for our test methods. 989 | 990 | === Looping 991 | 992 | The first feature to look at is the new forEach method available to any collection class. Here are a couple of examples that print out a Person list. 993 | 994 | [source,java] 995 | .Test01ForEach.java 996 | ---- 997 | 11 public class Test01ForEach { 998 | 12 999 | 13 public static void main(String[] args) { 1000 | 14 1001 | 15 List pl = Person.createShortList(); 1002 | 16 1003 | 17 System.out.println("\n=== Western Phone List ==="); 1004 | 18 pl.forEach( p -> p.printWesternName() ); 1005 | 19 1006 | 20 System.out.println("\n=== Eastern Phone List ==="); 1007 | 21 pl.forEach(Person::printEasternName); 1008 | 22 1009 | 23 System.out.println("\n=== Custom Phone List ==="); 1010 | 24 pl.forEach(p -> { System.out.println(p.printCustom(r -> "Name: " + r.getGivenName() + " EMail: " + r.getEmail())); }); 1011 | 25 1012 | 26 } 1013 | 27 1014 | 28 } 1015 | ---- 1016 | 1017 | The first example shows a standard lambda expression which calls the printWesternName method to print out each person in the list. The second example demonstrates a method reference. In a case where a method already exists to perform an operation on the class, this syntax can be used instead of the normal lambda expression syntax. Finally, the last example shows how the printCustom method can also be used in this situation. Notice the slight variation in variable names when one lambda expression is included in another. 1018 | 1019 | You can iterate through any collection this way. The basic structure is similar to the enhanced for loop. However, including an iteration mechanism within the class provides a number of benefits. 1020 | 1021 | === Chaining and Filters 1022 | 1023 | In addition to looping through the contents of a collection, you can chain methods together. The first method to look at is filter which takes a Predicate interface as a parameter. 1024 | 1025 | The following example loops though a List after first filtering the results. 1026 | 1027 | [source,java] 1028 | .Test02Filter.java 1029 | ---- 1030 | 9 public class Test02Filter { 1031 | 10 1032 | 11 public static void main(String[] args) { 1033 | 12 1034 | 13 List pl = Person.createShortList(); 1035 | 14 1036 | 15 SearchCriteria search = SearchCriteria.getInstance(); 1037 | 16 1038 | 17 System.out.println("\n=== Western Pilot Phone List ==="); 1039 | 18 1040 | 19 pl.stream().filter(search.getCriteria("allPilots")) 1041 | 20 .forEach(Person::printWesternName); 1042 | 21 1043 | 22 1044 | 23 System.out.println("\n=== Eastern Draftee Phone List ==="); 1045 | 24 1046 | 25 pl.stream().filter(search.getCriteria("allDraftees")) 1047 | 26 .forEach(Person::printEasternName); 1048 | 27 1049 | 28 } 1050 | 29 } 1051 | ---- 1052 | The first and last loops demonstrate how the List is filtered based on the search criteria. The output from the last loop looks like following: 1053 | 1054 | [source,xml] 1055 | ---- 1056 | === Eastern Draftee Phone List === 1057 | 1058 | Name: Baker Bob 1059 | Age: 21 Gender: MALE 1060 | EMail: bob.baker@example.com 1061 | Phone: 201-121-4678 1062 | Address: 44 4th St, Smallville, KS 12333 1063 | 1064 | Name: Doe John 1065 | Age: 25 Gender: MALE 1066 | EMail: john.doe@example.com 1067 | Phone: 202-123-4678 1068 | Address: 33 3rd St, Smallville, KS 12333 1069 | Getting Lazy 1070 | ---- 1071 | 1072 | These features are useful, but why add them to the collections classes when there is already a perfectly good for loop? By moving iteration features into a library, it allows the developers of Java to do more code optimizations. To explain further, a couple of terms need definitions. 1073 | 1074 | Laziness: In programming, laziness refers to processing only the objects that you want to process when you need to process them. In the previous example, the last loop is "lazy" because it loops only through the two Person objects left after the List is filtered. The code should be more efficient because the final processing step occurs only on the selected objects. 1075 | Eagerness: Code that performs operations on every object in a list is considered "eager". For example, an enhanced for loop that iterates through an entire list to process two objects, is considered a more "eager" approach. 1076 | By making looping part of the collections library, code can be better optimized for "lazy" operations when the opportunity arises. When a more eager approach makes sense (for example, computing a sum or an average), eager operations are still applied. This approach is a much more efficient and flexible than always using eager operations. 1077 | 1078 | ==== The stream Method 1079 | 1080 | In the previous code example, notice that the stream method is called before filtering and looping begin. This method takes a Collection as input and returns a java.util.stream.Stream interface as the output. A Stream represents a sequence of elements on which various methods can be chained. By default, once elements are consumed they are no longer available from the stream. Therefore, a chain of operations can occur only once on a particular Stream. In addition, a Stream can be serial(default) or parallel depending on the method called. An example of a parallel stream is included at the end of this section. 1081 | 1082 | ==== Mutation and Results 1083 | 1084 | As previously mentioned, a Stream is disposed of after its use. Therefore, the elements in a collection cannot be changed or mutated with a Stream. However, what if you want to keep elements returned from your chained operations? You can save them to a new collection. The following code shows how to do just that. 1085 | 1086 | [source,java] 1087 | .Test03toList.java 1088 | ---- 1089 | 10 public class Test03toList { 1090 | 11 1091 | 12 public static void main(String[] args) { 1092 | 13 1093 | 14 List pl = Person.createShortList(); 1094 | 15 1095 | 16 SearchCriteria search = SearchCriteria.getInstance(); 1096 | 17 1097 | 18 // Make a new list after filtering. 1098 | 19 List pilotList = pl 1099 | 20 .stream() 1100 | 21 .filter(search.getCriteria("allPilots")) 1101 | 22 .collect(Collectors.toList()); 1102 | 23 1103 | 24 System.out.println("\n=== Western Pilot Phone List ==="); 1104 | 25 pilotList.forEach(Person::printWesternName); 1105 | 26 1106 | 27 } 1107 | 28 1108 | 29 } 1109 | ---- 1110 | 1111 | The collect method is called with one parameter, the Collectors class. The Collectors class is able to return a List or Set based on the results of the stream. The example shows how the result of the stream is assigned to a new List which is iterated over. 1112 | 1113 | Calculating with map 1114 | 1115 | The map method is commonly used with filter. The method takes a property from a class and does something with it. The following example demonstrates this by performing calculations based on age. 1116 | 1117 | 1118 | .Test04Map.java 1119 | [source,java] 1120 | ---- 1121 | 10 public class Test04Map { 1122 | 11 1123 | 12 public static void main(String[] args) { 1124 | 13 List pl = Person.createShortList(); 1125 | 14 1126 | 15 SearchCriteria search = SearchCriteria.getInstance(); 1127 | 16 1128 | 17 // Calc average age of pilots old style 1129 | 18 System.out.println("== Calc Old Style =="); 1130 | 19 int sum = 0; 1131 | 20 int count = 0; 1132 | 21 1133 | 22 for (Person p:pl){ 1134 | 23 if (p.getAge() >= 23 && p.getAge() <= 65 ){ 1135 | 24 sum = sum + p.getAge(); 1136 | 25 count++; 1137 | 26 } 1138 | 27 } 1139 | 28 1140 | 29 long average = sum / count; 1141 | 30 System.out.println("Total Ages: " + sum); 1142 | 31 System.out.println("Average Age: " + average); 1143 | 32 1144 | 33 1145 | 34 // Get sum of ages 1146 | 35 System.out.println("\n== Calc New Style =="); 1147 | 36 long totalAge = pl 1148 | 37 .stream() 1149 | 38 .filter(search.getCriteria("allPilots")) 1150 | 39 .mapToInt(p -> p.getAge()) 1151 | 40 .sum(); 1152 | 41 1153 | 42 // Get average of ages 1154 | 43 OptionalDouble averageAge = pl 1155 | 44 .parallelStream() 1156 | 45 .filter(search.getCriteria("allPilots")) 1157 | 46 .mapToDouble(p -> p.getAge()) 1158 | 47 .average(); 1159 | 48 1160 | 49 System.out.println("Total Ages: " + totalAge); 1161 | 50 System.out.println("Average Age: " + averageAge.getAsDouble()); 1162 | 51 1163 | 52 } 1164 | 53 1165 | 54 } 1166 | ---- 1167 | 1168 | And the output from the class is: 1169 | 1170 | [source, xml] 1171 | ---- 1172 | == Calc Old Style 1173 | Total Ages: 150 1174 | Average Age: 37 1175 | 1176 | == Calc New Style 1177 | Total Ages: 150 1178 | Average Age: 37.5 1179 | ---- 1180 | 1181 | The program calculates the average age of pilots in our list. The first loop demonstrates the old style of calculating the number by using a for loop. The second loop uses the map method to get the age of each person in a serial stream. Notice that totalAge is a long. The map method returns an IntSteam object, which contains a sum method that returns a long. 1182 | 1183 | NOTE: To compute the average the second time, calculating the sum of ages is unnecessary. However, it is instructive to show an example with the sum method. 1184 | 1185 | The last loop computes the average age from the stream. Notice that the parallelStream method is used to get a parallel stream so that the values can be computed concurrently. The return type is a bit different here as well. 1186 | 1187 | 1188 | == Summary 1189 | 1190 | In this tutorial, you learned how to use: 1191 | 1192 | Anonymous inner classes in Java. 1193 | Lambda expressions to replace anonymous inner classes in Java SE 8. 1194 | The correct syntax for lambda expressions. 1195 | A Predicate interface to perform searches on a list. 1196 | A Function interface to process an object and produce a different type of object. 1197 | New features added to Collections in Java SE 8 that support lambda expressions. 1198 | Resources 1199 | 1200 | For further information on Java SE 8 and lambda expressions, see the following: 1201 | 1202 | Java 8 1203 | Project Lambda 1204 | State of the Lambda 1205 | State of the Lambda Collections 1206 | Jump-Starting Lambda JavaOne 2012 (You Tube) 1207 | To learn more about Java and related topics check out the Oracle Learning Library. 1208 | -------------------------------------------------------------------------------- /Lesson 1/README.adoc: -------------------------------------------------------------------------------- 1 | = Lesson 1: Lambda Expressions 2 | 3 | This lesson covers the new lambda expressions feature added to Java SE 8: 4 | 5 | . Why lambda expressions are needed in Java. 6 | . Why this feature was added to Java after twenty years. 7 | . The syntax of lambda expressions. 8 | . How to use lambda expressions and the rules that govern their use. 9 | . Examples of classes and methods that use lambda expressions like the new removeIf and replaceAll methods in the Collections API 10 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaCollectionExamples/LambdaCollectionExamples/build.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | Builds, tests, and runs the project LambdaCollectionExamples. 12 | 13 | 73 | 74 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaCollectionExamples/LambdaCollectionExamples/manifest.mf: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | X-COMMENT: Main-Class will be added automatically by build 3 | 4 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaCollectionExamples/LambdaCollectionExamples/nbproject/genfiles.properties: -------------------------------------------------------------------------------- 1 | build.xml.data.CRC32=f17b1921 2 | build.xml.script.CRC32=500de459 3 | build.xml.stylesheet.CRC32=8064a381@1.68.1.46 4 | # This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. 5 | # Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. 6 | nbproject/build-impl.xml.data.CRC32=f17b1921 7 | nbproject/build-impl.xml.script.CRC32=f1db7164 8 | nbproject/build-impl.xml.stylesheet.CRC32=5a01deb7@1.68.1.46 9 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaCollectionExamples/LambdaCollectionExamples/nbproject/private/config.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/Lesson 1/exercices/LambdaCollectionExamples/LambdaCollectionExamples/nbproject/private/config.properties -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaCollectionExamples/LambdaCollectionExamples/nbproject/private/private.properties: -------------------------------------------------------------------------------- 1 | compile.on.save=true 2 | do.depend=false 3 | do.jar=true 4 | javac.debug=true 5 | javadoc.preview=true 6 | user.properties.file=/home/mw119255/.netbeans/7.4/build.properties 7 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaCollectionExamples/LambdaCollectionExamples/nbproject/private/private.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaCollectionExamples/LambdaCollectionExamples/nbproject/project.properties: -------------------------------------------------------------------------------- 1 | annotation.processing.enabled=true 2 | annotation.processing.enabled.in.editor=false 3 | annotation.processing.processors.list= 4 | annotation.processing.run.all.processors=true 5 | annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output 6 | application.title=LambdaCollectionExamples 7 | application.vendor=mw119255 8 | build.classes.dir=${build.dir}/classes 9 | build.classes.excludes=**/*.java,**/*.form 10 | # This directory is removed when the project is cleaned: 11 | build.dir=build 12 | build.generated.dir=${build.dir}/generated 13 | build.generated.sources.dir=${build.dir}/generated-sources 14 | # Only compile against the classpath explicitly listed here: 15 | build.sysclasspath=ignore 16 | build.test.classes.dir=${build.dir}/test/classes 17 | build.test.results.dir=${build.dir}/test/results 18 | # Uncomment to specify the preferred debugger connection transport: 19 | #debug.transport=dt_socket 20 | debug.classpath=\ 21 | ${run.classpath} 22 | debug.test.classpath=\ 23 | ${run.test.classpath} 24 | # This directory is removed when the project is cleaned: 25 | dist.dir=dist 26 | dist.jar=${dist.dir}/LambdaCollectionExamples.jar 27 | dist.javadoc.dir=${dist.dir}/javadoc 28 | endorsed.classpath= 29 | excludes= 30 | includes=** 31 | jar.compress=false 32 | javac.classpath= 33 | # Space-separated list of extra javac options 34 | javac.compilerargs= 35 | javac.deprecation=false 36 | javac.processorpath=\ 37 | ${javac.classpath} 38 | javac.source=1.8 39 | javac.target=1.8 40 | javac.test.classpath=\ 41 | ${javac.classpath}:\ 42 | ${build.classes.dir} 43 | javac.test.processorpath=\ 44 | ${javac.test.classpath} 45 | javadoc.additionalparam= 46 | javadoc.author=false 47 | javadoc.encoding=${source.encoding} 48 | javadoc.noindex=false 49 | javadoc.nonavbar=false 50 | javadoc.notree=false 51 | javadoc.private=false 52 | javadoc.splitindex=true 53 | javadoc.use=true 54 | javadoc.version=false 55 | javadoc.windowtitle= 56 | main.class=com.example.lambda.Main 57 | manifest.file=manifest.mf 58 | meta.inf.dir=${src.dir}/META-INF 59 | mkdist.disabled=false 60 | platform.active=JDK_1.8 61 | run.classpath=\ 62 | ${javac.classpath}:\ 63 | ${build.classes.dir} 64 | # Space-separated list of JVM arguments used when running the project. 65 | # You may also define separate properties like run-sys-prop.name=value instead of -Dname=value. 66 | # To set system properties for unit tests define test-sys-prop.name=value: 67 | run.jvmargs= 68 | run.test.classpath=\ 69 | ${javac.test.classpath}:\ 70 | ${build.test.classes.dir} 71 | source.encoding=UTF-8 72 | src.dir=src 73 | test.src.dir=test 74 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaCollectionExamples/LambdaCollectionExamples/nbproject/project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | org.netbeans.modules.java.j2seproject 4 | 5 | 6 | LambdaCollectionExamples 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaCollectionExamples/LambdaCollectionExamples/src/com/example/lambda/Gender.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | /** 4 | * @author MikeW 5 | */ 6 | public enum Gender { MALE, FEMALE } 7 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaCollectionExamples/LambdaCollectionExamples/src/com/example/lambda/Main.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | /** 4 | * @author MikeW 5 | */ 6 | public class Main { 7 | 8 | public static void main(String[] args) { 9 | 10 | Test01ForEach.main(args); 11 | Test02Filter.main(args); 12 | Test03toList.main(args); 13 | Test04Map.main(args); 14 | 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaCollectionExamples/LambdaCollectionExamples/src/com/example/lambda/Person.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.function.Function; 6 | import java.util.Map; 7 | import java.util.HashMap; 8 | 9 | 10 | /** 11 | * @author MikeW 12 | */ 13 | public class Person { 14 | private String givenName; 15 | private String surName; 16 | private int age; 17 | private Gender gender; 18 | private String eMail; 19 | private String phone; 20 | private String address; 21 | 22 | 23 | public static class Builder{ 24 | 25 | private String givenName=""; 26 | private String surName=""; 27 | private int age = 0; 28 | private Gender gender = Gender.FEMALE; 29 | private String eMail = ""; 30 | private String phone = ""; 31 | private String address = ""; 32 | 33 | public Person.Builder givenName(String givenName){ 34 | this.givenName = givenName; 35 | return this; 36 | } 37 | 38 | public Person.Builder surName(String surName){ 39 | this.surName = surName; 40 | return this; 41 | } 42 | 43 | public Person.Builder age (int val){ 44 | age = val; 45 | return this; 46 | } 47 | 48 | public Person.Builder gender(Gender val){ 49 | gender = val; 50 | return this; 51 | } 52 | 53 | public Person.Builder email(String val){ 54 | eMail = val; 55 | return this; 56 | } 57 | 58 | public Person.Builder phoneNumber(String val){ 59 | phone = val; 60 | return this; 61 | } 62 | 63 | public Person.Builder address(String val){ 64 | address = val; 65 | return this; 66 | } 67 | 68 | public Person build(){ 69 | return new Person(this); 70 | } 71 | } 72 | 73 | 74 | 75 | private Person(){ 76 | super(); 77 | } 78 | 79 | private Person(Person.Builder builder){ 80 | 81 | givenName = builder.givenName; 82 | surName = builder.surName; 83 | age = builder.age; 84 | gender = builder.gender; 85 | eMail = builder.eMail; 86 | phone = builder.phone; 87 | address = builder.address; 88 | } 89 | 90 | public String getGivenName(){ 91 | return givenName; 92 | } 93 | 94 | public String getSurName(){ 95 | return surName; 96 | } 97 | 98 | public int getAge(){ 99 | return age; 100 | } 101 | 102 | public Gender getGender(){ 103 | return gender; 104 | } 105 | 106 | public String getEmail(){ 107 | return eMail; 108 | } 109 | 110 | public String getPhone(){ 111 | return phone; 112 | } 113 | 114 | public String getAddress(){ 115 | return address; 116 | } 117 | 118 | public void print(){ 119 | System.out.println( 120 | "\nName: " + givenName + " " + surName + "\n" + 121 | "Age: " + age + "\n" + 122 | "Gender: " + gender + "\n" + 123 | "eMail: " + eMail + "\n" + 124 | "Phone: " + phone + "\n" + 125 | "Address: " + address + "\n" 126 | ); 127 | } 128 | 129 | public String printCustom(Function f){ 130 | return f.apply(this); 131 | } 132 | 133 | 134 | public void printWesternName(){ 135 | 136 | System.out.println("\nName: " + this.getGivenName() + " " + this.getSurName() + "\n" + 137 | "Age: " + this.getAge() + " " + "Gender: " + this.getGender() + "\n" + 138 | "EMail: " + this.getEmail() + "\n" + 139 | "Phone: " + this.getPhone() + "\n" + 140 | "Address: " + this.getAddress()); 141 | } 142 | 143 | 144 | public void printEasternName(){ 145 | 146 | System.out.println("\nName: " + this.getSurName() + " " + this.getGivenName() + "\n" + 147 | "Age: " + this.getAge() + " " + "Gender: " + this.getGender() + "\n" + 148 | "EMail: " + this.getEmail() + "\n" + 149 | "Phone: " + this.getPhone() + "\n" + 150 | "Address: " + this.getAddress()); 151 | } 152 | 153 | 154 | @Override 155 | public String toString(){ 156 | return "Name: " + givenName + " " + surName + "\n" + "Age: " + age + " Gender: " + gender + "\n" + "eMail: " + eMail + "\n"; 157 | } 158 | 159 | public static List createShortList(){ 160 | List people = new ArrayList<>(); 161 | 162 | people.add( 163 | new Person.Builder() 164 | .givenName("Bob") 165 | .surName("Baker") 166 | .age(21) 167 | .gender(Gender.MALE) 168 | .email("bob.baker@example.com") 169 | .phoneNumber("201-121-4678") 170 | .address("44 4th St, Smallville, KS 12333") 171 | .build() 172 | ); 173 | 174 | people.add( 175 | new Person.Builder() 176 | .givenName("Jane") 177 | .surName("Doe") 178 | .age(25) 179 | .gender(Gender.FEMALE) 180 | .email("jane.doe@example.com") 181 | .phoneNumber("202-123-4678") 182 | .address("33 3rd St, Smallville, KS 12333") 183 | .build() 184 | ); 185 | 186 | people.add( 187 | new Person.Builder() 188 | .givenName("John") 189 | .surName("Doe") 190 | .age(25) 191 | .gender(Gender.MALE) 192 | .email("john.doe@example.com") 193 | .phoneNumber("202-123-4678") 194 | .address("33 3rd St, Smallville, KS 12333") 195 | .build() 196 | ); 197 | 198 | people.add( 199 | new Person.Builder() 200 | .givenName("James") 201 | .surName("Johnson") 202 | .age(45) 203 | .gender(Gender.MALE) 204 | .email("james.johnson@example.com") 205 | .phoneNumber("333-456-1233") 206 | .address("201 2nd St, New York, NY 12111") 207 | .build() 208 | ); 209 | 210 | people.add( 211 | new Person.Builder() 212 | .givenName("Joe") 213 | .surName("Bailey") 214 | .age(67) 215 | .gender(Gender.MALE) 216 | .email("joebob.bailey@example.com") 217 | .phoneNumber("112-111-1111") 218 | .address("111 1st St, Town, CA 11111") 219 | .build() 220 | ); 221 | 222 | people.add( 223 | new Person.Builder() 224 | .givenName("Phil") 225 | .surName("Smith") 226 | .age(55) 227 | .gender(Gender.MALE) 228 | .email("phil.smith@examp;e.com") 229 | .phoneNumber("222-33-1234") 230 | .address("22 2nd St, New Park, CO 222333") 231 | .build() 232 | ); 233 | 234 | people.add( 235 | new Person.Builder() 236 | .givenName("Betty") 237 | .surName("Jones") 238 | .age(85) 239 | .gender(Gender.FEMALE) 240 | .email("betty.jones@example.com") 241 | .phoneNumber("211-33-1234") 242 | .address("22 4th St, New Park, CO 222333") 243 | .build() 244 | ); 245 | 246 | 247 | return people; 248 | } 249 | 250 | } 251 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaCollectionExamples/LambdaCollectionExamples/src/com/example/lambda/SearchCriteria.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.function.Predicate; 6 | 7 | /** 8 | * 9 | * @author MikeW 10 | */ 11 | public class SearchCriteria { 12 | 13 | private final Map> searchMap = new HashMap<>(); 14 | 15 | private SearchCriteria() { 16 | super(); 17 | initSearchMap(); 18 | } 19 | 20 | private void initSearchMap() { 21 | Predicate allDrivers = p -> p.getAge() >= 16; 22 | Predicate allDraftees = p -> p.getAge() >= 18 && p.getAge() <= 25 && p.getGender() == Gender.MALE; 23 | Predicate allPilots = p -> p.getAge() >= 23 && p.getAge() <= 65; 24 | 25 | searchMap.put("allDrivers", allDrivers); 26 | searchMap.put("allDraftees", allDraftees); 27 | searchMap.put("allPilots", allPilots); 28 | 29 | } 30 | 31 | public Predicate getCriteria(String PredicateName) { 32 | Predicate target; 33 | 34 | target = searchMap.get(PredicateName); 35 | 36 | if (target == null) { 37 | 38 | System.out.println("Search Criteria not found... "); 39 | System.exit(1); 40 | 41 | } 42 | 43 | return target; 44 | 45 | } 46 | 47 | public static SearchCriteria getInstance() { 48 | return new SearchCriteria(); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaCollectionExamples/LambdaCollectionExamples/src/com/example/lambda/Test01ForEach.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | import java.util.function.Function; 6 | 7 | /** 8 | * 9 | * @author MikeW 10 | */ 11 | public class Test01ForEach { 12 | 13 | public static void main(String[] args) { 14 | 15 | List pl = Person.createShortList(); 16 | 17 | System.out.println("\n=== Western Phone List ==="); 18 | pl.forEach( p -> p.printWesternName() ); 19 | 20 | System.out.println("\n=== Eastern Phone List ==="); 21 | pl.forEach(Person::printEasternName); 22 | 23 | System.out.println("\n=== Custom Phone List ==="); 24 | pl.forEach(p -> { System.out.println(p.printCustom(r -> "Name: " + r.getGivenName() + " EMail: " + r.getEmail())); }); 25 | 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaCollectionExamples/LambdaCollectionExamples/src/com/example/lambda/Test02Filter.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * 7 | * @author MikeW 8 | */ 9 | public class Test02Filter { 10 | 11 | public static void main(String[] args) { 12 | 13 | List pl = Person.createShortList(); 14 | 15 | SearchCriteria search = SearchCriteria.getInstance(); 16 | 17 | System.out.println("\n=== Western Pilot Phone List ==="); 18 | 19 | pl.stream().filter(search.getCriteria("allPilots")) 20 | .forEach(Person::printWesternName); 21 | 22 | 23 | System.out.println("\n=== Eastern Draftee Phone List ==="); 24 | 25 | pl.stream().filter(search.getCriteria("allDraftees")) 26 | .forEach(Person::printEasternName); 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaCollectionExamples/LambdaCollectionExamples/src/com/example/lambda/Test03toList.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | import java.util.List; 4 | import java.util.stream.Collectors; 5 | 6 | /** 7 | * 8 | * @author MikeW 9 | */ 10 | public class Test03toList { 11 | 12 | public static void main(String[] args) { 13 | 14 | List pl = Person.createShortList(); 15 | 16 | SearchCriteria search = SearchCriteria.getInstance(); 17 | 18 | // Make a new list after filtering. 19 | List pilotList = pl 20 | .stream() 21 | .filter(search.getCriteria("allPilots")) 22 | .collect(Collectors.toList()); 23 | 24 | System.out.println("\n=== Western Pilot Phone List ==="); 25 | pilotList.forEach(Person::printWesternName); 26 | 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaCollectionExamples/LambdaCollectionExamples/src/com/example/lambda/Test04Map.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | import java.util.List; 4 | import java.util.OptionalDouble; 5 | 6 | /** 7 | * 8 | * @author MikeW 9 | */ 10 | public class Test04Map { 11 | 12 | public static void main(String[] args) { 13 | List pl = Person.createShortList(); 14 | 15 | SearchCriteria search = SearchCriteria.getInstance(); 16 | 17 | // Calc average age of pilots old style 18 | System.out.println("== Calc Old Style =="); 19 | int sum = 0; 20 | int count = 0; 21 | 22 | for (Person p:pl){ 23 | if (p.getAge() >= 23 && p.getAge() <= 65 ){ 24 | sum = sum + p.getAge(); 25 | count++; 26 | } 27 | } 28 | 29 | long average = sum / count; 30 | System.out.println("Total Ages: " + sum); 31 | System.out.println("Average Age: " + average); 32 | 33 | 34 | // Get sum of ages 35 | System.out.println("\n== Calc New Style =="); 36 | long totalAge = pl 37 | .stream() 38 | .filter(search.getCriteria("allPilots")) 39 | .mapToInt(p -> p.getAge()) 40 | .sum(); 41 | 42 | // Get average of ages 43 | OptionalDouble averageAge = pl 44 | .parallelStream() 45 | .filter(search.getCriteria("allPilots")) 46 | .mapToDouble(p -> p.getAge()) 47 | .average(); 48 | 49 | System.out.println("Total Ages: " + totalAge); 50 | System.out.println("Average Age: " + averageAge.getAsDouble()); 51 | 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaExamples01/LambdaExamples01/build.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | Builds, tests, and runs the project LambdaExamples01. 12 | 13 | 73 | 74 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaExamples01/LambdaExamples01/manifest.mf: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | X-COMMENT: Main-Class will be added automatically by build 3 | 4 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaExamples01/LambdaExamples01/nbproject/genfiles.properties: -------------------------------------------------------------------------------- 1 | build.xml.data.CRC32=c1657c2b 2 | build.xml.script.CRC32=ca9887be 3 | build.xml.stylesheet.CRC32=8064a381@1.68.1.46 4 | # This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. 5 | # Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. 6 | nbproject/build-impl.xml.data.CRC32=c1657c2b 7 | nbproject/build-impl.xml.script.CRC32=20882f00 8 | nbproject/build-impl.xml.stylesheet.CRC32=5a01deb7@1.68.1.46 9 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaExamples01/LambdaExamples01/nbproject/private/config.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/Lesson 1/exercices/LambdaExamples01/LambdaExamples01/nbproject/private/config.properties -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaExamples01/LambdaExamples01/nbproject/private/private.properties: -------------------------------------------------------------------------------- 1 | compile.on.save=false 2 | do.depend=false 3 | do.jar=true 4 | javac.debug=true 5 | javadoc.preview=true 6 | user.properties.file=/home/mw119255/.netbeans/7.4/build.properties 7 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaExamples01/LambdaExamples01/nbproject/private/private.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaExamples01/LambdaExamples01/nbproject/project.properties: -------------------------------------------------------------------------------- 1 | annotation.processing.enabled=true 2 | annotation.processing.enabled.in.editor=false 3 | annotation.processing.processors.list= 4 | annotation.processing.run.all.processors=true 5 | annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output 6 | application.title=LambdaExamples01 7 | application.vendor=mw119255 8 | build.classes.dir=${build.dir}/classes 9 | build.classes.excludes=**/*.java,**/*.form 10 | # This directory is removed when the project is cleaned: 11 | build.dir=build 12 | build.generated.dir=${build.dir}/generated 13 | build.generated.sources.dir=${build.dir}/generated-sources 14 | # Only compile against the classpath explicitly listed here: 15 | build.sysclasspath=ignore 16 | build.test.classes.dir=${build.dir}/test/classes 17 | build.test.results.dir=${build.dir}/test/results 18 | # Uncomment to specify the preferred debugger connection transport: 19 | #debug.transport=dt_socket 20 | debug.classpath=\ 21 | ${run.classpath} 22 | debug.test.classpath=\ 23 | ${run.test.classpath} 24 | # This directory is removed when the project is cleaned: 25 | dist.dir=dist 26 | dist.jar=${dist.dir}/LambdaExamples01.jar 27 | dist.javadoc.dir=${dist.dir}/javadoc 28 | endorsed.classpath= 29 | excludes= 30 | includes=** 31 | jar.compress=false 32 | javac.classpath= 33 | # Space-separated list of extra javac options 34 | javac.compilerargs= 35 | javac.deprecation=false 36 | javac.processorpath=\ 37 | ${javac.classpath} 38 | javac.source=1.8 39 | javac.target=1.8 40 | javac.test.classpath=\ 41 | ${javac.classpath}:\ 42 | ${build.classes.dir} 43 | javac.test.processorpath=\ 44 | ${javac.test.classpath} 45 | javadoc.additionalparam= 46 | javadoc.author=false 47 | javadoc.encoding=${source.encoding} 48 | javadoc.noindex=false 49 | javadoc.nonavbar=false 50 | javadoc.notree=false 51 | javadoc.private=false 52 | javadoc.splitindex=true 53 | javadoc.use=true 54 | javadoc.version=false 55 | javadoc.windowtitle= 56 | main.class=com.example.lambda.Main 57 | manifest.file=manifest.mf 58 | meta.inf.dir=${src.dir}/META-INF 59 | mkdist.disabled=false 60 | platform.active=JDK_1.8 61 | run.classpath=\ 62 | ${javac.classpath}:\ 63 | ${build.classes.dir} 64 | # Space-separated list of JVM arguments used when running the project. 65 | # You may also define separate properties like run-sys-prop.name=value instead of -Dname=value. 66 | # To set system properties for unit tests define test-sys-prop.name=value: 67 | run.jvmargs= 68 | run.test.classpath=\ 69 | ${javac.test.classpath}:\ 70 | ${build.test.classes.dir} 71 | source.encoding=UTF-8 72 | src.dir=src 73 | test.src.dir=test 74 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaExamples01/LambdaExamples01/nbproject/project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | org.netbeans.modules.java.j2seproject 4 | 5 | 6 | LambdaExamples01 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaExamples01/LambdaExamples01/src/com/example/lambda/#Untitled-1#: -------------------------------------------------------------------------------- 1 | 2 | 3 | ListenerTest.java 4 | 84 | 85 | 86 |
13 public class ListenerTest {
 87 | 14   public static void main(String[] args) {
 88 | 15         
 89 | 16     JButton testButton = new JButton("Test Button");
 90 | 17     testButton.addActionListener(new ActionListener(){
 91 | 18     @Override public void actionPerformed(ActionEvent ae){
 92 | 19         System.out.println("Click Detected by Anon Class");
 93 | 20       }
 94 | 21     });
 95 | 22     
 96 | 23     testButton.addActionListener(e -> System.out.println("Click Detected by Lambda Listner"));
 97 | 24     
 98 | 25     // Swing stuff
 99 | 26     JFrame frame = new JFrame("Listener Test");
100 | 27     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
101 | 28     frame.add(testButton, BorderLayout.CENTER);
102 | 29     frame.pack();
103 | 30     frame.setVisible(true);
104 | 31     
105 | 32   }
106 | 33 }
107 | 
108 | 109 | 110 | 111 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaExamples01/LambdaExamples01/src/com/example/lambda/ComparatorTest.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | import java.util.Collections; 4 | import java.util.List; 5 | import java.util.Comparator; 6 | 7 | /** 8 | * @author MikeW 9 | */ 10 | public class ComparatorTest { 11 | 12 | public static void main(String[] args) { 13 | 14 | List personList = Person.createShortList(); 15 | 16 | // Sort with Inner Class 17 | Collections.sort(personList, new Comparator(){ 18 | public int compare(Person p1, Person p2){ 19 | return p1.getSurName().compareTo(p2.getSurName()); 20 | } 21 | }); 22 | 23 | System.out.println("=== Sorted Asc SurName ==="); 24 | for(Person p:personList){ 25 | p.printName(); 26 | } 27 | 28 | // Use Lambda instead 29 | 30 | // Print Asc 31 | System.out.println("=== Sorted Asc SurName ==="); 32 | Collections.sort(personList, (Person p1, Person p2) -> p1.getSurName().compareTo(p2.getSurName())); 33 | 34 | for(Person p:personList){ 35 | p.printName(); 36 | } 37 | 38 | // Print Desc 39 | System.out.println("=== Sorted Desc SurName ==="); 40 | Collections.sort(personList, (p1, p2) -> p2.getSurName().compareTo(p1.getSurName())); 41 | 42 | for(Person p:personList){ 43 | p.printName(); 44 | } 45 | 46 | } 47 | } -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaExamples01/LambdaExamples01/src/com/example/lambda/Gender.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | /** 4 | * @author MikeW 5 | */ 6 | public enum Gender { MALE, FEMALE } 7 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaExamples01/LambdaExamples01/src/com/example/lambda/ListenerTest.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | import java.awt.BorderLayout; 4 | import java.awt.event.ActionEvent; 5 | import java.awt.event.ActionListener; 6 | import javax.swing.JButton; 7 | import javax.swing.JFrame; 8 | 9 | /** 10 | * 11 | * @author MikeW 12 | */ 13 | public class ListenerTest { 14 | public static void main(String[] args) { 15 | 16 | JButton testButton = new JButton("Test Button"); 17 | testButton.addActionListener(new ActionListener(){ 18 | @Override public void actionPerformed(ActionEvent ae){ 19 | System.out.println("Click Detected by Anon Class"); 20 | } 21 | }); 22 | 23 | testButton.addActionListener(e -> System.out.println("Click Detected by Lambda Listner")); 24 | 25 | // Swing stuff 26 | JFrame frame = new JFrame("Listener Test"); 27 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 28 | frame.add(testButton, BorderLayout.CENTER); 29 | frame.pack(); 30 | frame.setVisible(true); 31 | 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaExamples01/LambdaExamples01/src/com/example/lambda/Main.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | /** 4 | * @author mikew 5 | */ 6 | public class Main { 7 | 8 | public static void main(String[] args) { 9 | 10 | RunnableTest.main(args); 11 | ComparatorTest.main(args); 12 | ListenerTest.main(args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaExamples01/LambdaExamples01/src/com/example/lambda/Person.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * @author MikeW 8 | */ 9 | public class Person { 10 | private String givenName; 11 | private String surName; 12 | private int age; 13 | private Gender gender; 14 | private String eMail; 15 | private String phone; 16 | private String address; 17 | 18 | public static class Builder{ 19 | 20 | private String givenName=""; 21 | private String surName=""; 22 | private int age = 0; 23 | private Gender gender = Gender.FEMALE; 24 | private String eMail = ""; 25 | private String phone = ""; 26 | private String address = ""; 27 | 28 | public Person.Builder givenName(String givenName){ 29 | this.givenName = givenName; 30 | return this; 31 | } 32 | 33 | public Person.Builder surName(String surName){ 34 | this.surName = surName; 35 | return this; 36 | } 37 | 38 | public Person.Builder age (int val){ 39 | age = val; 40 | return this; 41 | } 42 | 43 | public Person.Builder gender(Gender val){ 44 | gender = val; 45 | return this; 46 | } 47 | 48 | public Person.Builder email(String val){ 49 | eMail = val; 50 | return this; 51 | } 52 | 53 | public Person.Builder phoneNumber(String val){ 54 | phone = val; 55 | return this; 56 | } 57 | 58 | public Person.Builder address(String val){ 59 | address = val; 60 | return this; 61 | } 62 | 63 | public Person build(){ 64 | return new Person(this); 65 | } 66 | } 67 | 68 | private Person(){ 69 | super(); 70 | } 71 | 72 | private Person(Person.Builder builder){ 73 | givenName = builder.givenName; 74 | surName = builder.surName; 75 | age = builder.age; 76 | gender = builder.gender; 77 | eMail = builder.eMail; 78 | phone = builder.phone; 79 | address = builder.address; 80 | 81 | } 82 | 83 | public String getGivenName(){ 84 | return givenName; 85 | } 86 | 87 | public String getSurName(){ 88 | return surName; 89 | } 90 | 91 | public int getAge(){ 92 | return age; 93 | } 94 | 95 | public void print(){ 96 | System.out.println( 97 | "\nName: " + givenName + " " + surName + "\n" + 98 | "Age: " + age + "\n" + 99 | "Gender: " + gender + "\n" + 100 | "eMail: " + eMail + "\n" + 101 | "Phone: " + phone + "\n" + 102 | "Address: " + address + "\n" 103 | ); 104 | } 105 | 106 | public void printName(){ 107 | System.out.println( 108 | "Name: " + givenName + " " + surName); 109 | } 110 | 111 | @Override 112 | public String toString(){ 113 | return "Name: " + givenName + " " + surName + "\n" + "Age: " + age + " Gender: " + gender + "\n" + "eMail: " + eMail + "\n" + "Address: " + address + "\n"; 114 | } 115 | 116 | 117 | public static List createShortList(){ 118 | List people = new ArrayList<>(); 119 | 120 | people.add( 121 | new Person.Builder() 122 | .givenName("Bob") 123 | .surName("Baker") 124 | .age(21) 125 | .gender(Gender.MALE) 126 | .email("bob.baker@example.com") 127 | .phoneNumber("201-121-4678") 128 | .address("44 4th St, Smallville, KS 12333") 129 | .build() 130 | ); 131 | 132 | people.add( 133 | new Person.Builder() 134 | .givenName("Jane") 135 | .surName("Doe") 136 | .age(25) 137 | .gender(Gender.FEMALE) 138 | .email("jane.doe@example.com") 139 | .phoneNumber("202-123-4678") 140 | .address("33 3rd St, Smallville, KS 12333") 141 | .build() 142 | ); 143 | 144 | people.add( 145 | new Person.Builder() 146 | .givenName("John") 147 | .surName("Doe") 148 | .age(25) 149 | .gender(Gender.MALE) 150 | .email("john.doe@example.com") 151 | .phoneNumber("202-123-4678") 152 | .address("33 3rd St, Smallville, KS 12333") 153 | .build() 154 | ); 155 | 156 | people.add( 157 | new Person.Builder() 158 | .givenName("James") 159 | .surName("Johnson") 160 | .age(45) 161 | .gender(Gender.MALE) 162 | .email("james.johnson@example.com") 163 | .phoneNumber("333-456-1233") 164 | .address("201 2nd St, New York, NY 12111") 165 | .build() 166 | ); 167 | 168 | people.add( 169 | new Person.Builder() 170 | .givenName("Joe") 171 | .surName("Bailey") 172 | .age(67) 173 | .gender(Gender.MALE) 174 | .email("joebob.bailey@example.com") 175 | .phoneNumber("112-111-1111") 176 | .address("111 1st St, Town, CA 11111") 177 | .build() 178 | ); 179 | 180 | people.add( 181 | new Person.Builder() 182 | .givenName("Phil") 183 | .surName("Smith") 184 | .age(55) 185 | .gender(Gender.MALE) 186 | .email("phil.smith@examp;e.com") 187 | .phoneNumber("222-33-1234") 188 | .address("22 2nd St, New Park, CO 222333") 189 | .build() 190 | ); 191 | 192 | people.add( 193 | new Person.Builder() 194 | .givenName("Betty") 195 | .surName("Jones") 196 | .age(85) 197 | .gender(Gender.FEMALE) 198 | .email("betty.jones@example.com") 199 | .phoneNumber("211-33-1234") 200 | .address("22 4th St, New Park, CO 222333") 201 | .build() 202 | ); 203 | 204 | 205 | return people; 206 | } 207 | 208 | } 209 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaExamples01/LambdaExamples01/src/com/example/lambda/RunnableTest.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | /** 4 | * @author MikeW 5 | */ 6 | public class RunnableTest { 7 | public static void main(String[] args) { 8 | 9 | System.out.println("=== RunnableTest ==="); 10 | 11 | // Anonymous Runnable 12 | Runnable r1 = new Runnable(){ 13 | 14 | @Override 15 | public void run(){ 16 | System.out.println("Hello world one!"); 17 | } 18 | }; 19 | 20 | // Lambda Runnable 21 | Runnable r2 = () -> System.out.println("Hello world two!"); 22 | 23 | // Run em! 24 | r1.run(); 25 | r2.run(); 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaFunctionExamples/LambdaFunctionExamples/build.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | Builds, tests, and runs the project LambdaFunctionExamples. 12 | 13 | 73 | 74 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaFunctionExamples/LambdaFunctionExamples/manifest.mf: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | X-COMMENT: Main-Class will be added automatically by build 3 | 4 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaFunctionExamples/LambdaFunctionExamples/nbproject/genfiles.properties: -------------------------------------------------------------------------------- 1 | build.xml.data.CRC32=da28f879 2 | build.xml.script.CRC32=1167ca31 3 | build.xml.stylesheet.CRC32=8064a381@1.68.1.46 4 | # This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. 5 | # Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. 6 | nbproject/build-impl.xml.data.CRC32=da28f879 7 | nbproject/build-impl.xml.script.CRC32=ced0b415 8 | nbproject/build-impl.xml.stylesheet.CRC32=5a01deb7@1.68.1.46 9 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaFunctionExamples/LambdaFunctionExamples/nbproject/private/config.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/Lesson 1/exercices/LambdaFunctionExamples/LambdaFunctionExamples/nbproject/private/config.properties -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaFunctionExamples/LambdaFunctionExamples/nbproject/private/private.properties: -------------------------------------------------------------------------------- 1 | compile.on.save=true 2 | do.depend=false 3 | do.jar=true 4 | javac.debug=true 5 | javadoc.preview=true 6 | user.properties.file=/home/mw119255/.netbeans/7.4/build.properties 7 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaFunctionExamples/LambdaFunctionExamples/nbproject/private/private.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaFunctionExamples/LambdaFunctionExamples/nbproject/project.properties: -------------------------------------------------------------------------------- 1 | annotation.processing.enabled=true 2 | annotation.processing.enabled.in.editor=false 3 | annotation.processing.processors.list= 4 | annotation.processing.run.all.processors=true 5 | annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output 6 | application.title=LambdaFunctionExamples 7 | application.vendor=mw119255 8 | build.classes.dir=${build.dir}/classes 9 | build.classes.excludes=**/*.java,**/*.form 10 | # This directory is removed when the project is cleaned: 11 | build.dir=build 12 | build.generated.dir=${build.dir}/generated 13 | build.generated.sources.dir=${build.dir}/generated-sources 14 | # Only compile against the classpath explicitly listed here: 15 | build.sysclasspath=ignore 16 | build.test.classes.dir=${build.dir}/test/classes 17 | build.test.results.dir=${build.dir}/test/results 18 | # Uncomment to specify the preferred debugger connection transport: 19 | #debug.transport=dt_socket 20 | debug.classpath=\ 21 | ${run.classpath} 22 | debug.test.classpath=\ 23 | ${run.test.classpath} 24 | # This directory is removed when the project is cleaned: 25 | dist.dir=dist 26 | dist.jar=${dist.dir}/LambdaFunctionExamples.jar 27 | dist.javadoc.dir=${dist.dir}/javadoc 28 | endorsed.classpath= 29 | excludes= 30 | includes=** 31 | jar.compress=false 32 | javac.classpath= 33 | # Space-separated list of extra javac options 34 | javac.compilerargs= 35 | javac.deprecation=false 36 | javac.processorpath=\ 37 | ${javac.classpath} 38 | javac.source=1.8 39 | javac.target=1.8 40 | javac.test.classpath=\ 41 | ${javac.classpath}:\ 42 | ${build.classes.dir} 43 | javac.test.processorpath=\ 44 | ${javac.test.classpath} 45 | javadoc.additionalparam= 46 | javadoc.author=false 47 | javadoc.encoding=${source.encoding} 48 | javadoc.noindex=false 49 | javadoc.nonavbar=false 50 | javadoc.notree=false 51 | javadoc.private=false 52 | javadoc.splitindex=true 53 | javadoc.use=true 54 | javadoc.version=false 55 | javadoc.windowtitle= 56 | main.class=com.example.lambda.Main 57 | manifest.file=manifest.mf 58 | meta.inf.dir=${src.dir}/META-INF 59 | mkdist.disabled=false 60 | platform.active=JDK_1.8 61 | run.classpath=\ 62 | ${javac.classpath}:\ 63 | ${build.classes.dir} 64 | # Space-separated list of JVM arguments used when running the project. 65 | # You may also define separate properties like run-sys-prop.name=value instead of -Dname=value. 66 | # To set system properties for unit tests define test-sys-prop.name=value: 67 | run.jvmargs= 68 | run.test.classpath=\ 69 | ${javac.test.classpath}:\ 70 | ${build.test.classes.dir} 71 | source.encoding=UTF-8 72 | src.dir=src 73 | test.src.dir=test 74 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaFunctionExamples/LambdaFunctionExamples/nbproject/project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | org.netbeans.modules.java.j2seproject 4 | 5 | 6 | LambdaFunctionExamples 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaFunctionExamples/LambdaFunctionExamples/src/com/example/lambda/Gender.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | /** 4 | * @author MikeW 5 | */ 6 | public enum Gender { MALE, FEMALE } 7 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaFunctionExamples/LambdaFunctionExamples/src/com/example/lambda/Main.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | /** 4 | * @author MikeW 5 | */ 6 | public class Main { 7 | 8 | public static void main(String[] args) { 9 | 10 | NameTestOld.main(args); 11 | NameTestNew.main(args); 12 | 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaFunctionExamples/LambdaFunctionExamples/src/com/example/lambda/NameTestNew.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | import java.util.List; 4 | import java.util.function.Function; 5 | 6 | /** 7 | * @author MikeW 8 | */ 9 | public class NameTestNew { 10 | 11 | public static void main(String[] args) { 12 | 13 | System.out.println("\n==== NameTestNew ==="); 14 | 15 | List list1 = Person.createShortList(); 16 | 17 | // Print Custom First Name and e-mail 18 | System.out.println("===Custom List==="); 19 | for (Person person:list1){ 20 | System.out.println( 21 | person.printCustom(p -> "Name: " + p.getGivenName() + " EMail: " + p.getEmail()) 22 | ); 23 | } 24 | 25 | 26 | // Define Western and Eastern Lambdas 27 | 28 | Function westernStyle = p -> { 29 | return "\nName: " + p.getGivenName() + " " + p.getSurName() + "\n" + 30 | "Age: " + p.getAge() + " " + "Gender: " + p.getGender() + "\n" + 31 | "EMail: " + p.getEmail() + "\n" + 32 | "Phone: " + p.getPhone() + "\n" + 33 | "Address: " + p.getAddress(); 34 | }; 35 | 36 | Function easternStyle = p -> "\nName: " + p.getSurName() + " " 37 | + p.getGivenName() + "\n" + "Age: " + p.getAge() + " " + 38 | "Gender: " + p.getGender() + "\n" + 39 | "EMail: " + p.getEmail() + "\n" + 40 | "Phone: " + p.getPhone() + "\n" + 41 | "Address: " + p.getAddress(); 42 | 43 | // Print Western List 44 | System.out.println("\n===Western List==="); 45 | for (Person person:list1){ 46 | System.out.println( 47 | person.printCustom(westernStyle) 48 | ); 49 | } 50 | 51 | // Print Eastern List 52 | System.out.println("\n===Eastern List==="); 53 | for (Person person:list1){ 54 | System.out.println( 55 | person.printCustom(easternStyle) 56 | ); 57 | } 58 | 59 | 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaFunctionExamples/LambdaFunctionExamples/src/com/example/lambda/NameTestOld.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | import java.util.List; 4 | import java.util.function.Function; 5 | 6 | /** 7 | * @author MikeW 8 | */ 9 | public class NameTestOld { 10 | 11 | public static void main(String[] args) { 12 | 13 | System.out.println("\n==== NameTestOld ==="); 14 | 15 | List list1 = Person.createShortList(); 16 | 17 | // Print Names Western 18 | System.out.println("\n===Print Western Names==="); 19 | for (Person person:list1){ 20 | person.printWesternName(); 21 | } 22 | 23 | // Print Names Eastern 24 | System.out.println("\n===Print Eastern Names==="); 25 | for (Person person:list1){ 26 | person.printEasternName(); 27 | } 28 | 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /Lesson 1/exercices/LambdaFunctionExamples/LambdaFunctionExamples/src/com/example/lambda/Person.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.function.Function; 6 | 7 | /** 8 | * @author MikeW 9 | */ 10 | public class Person { 11 | private String givenName; 12 | private String surName; 13 | private int age; 14 | private Gender gender; 15 | private String eMail; 16 | private String phone; 17 | private String address; 18 | 19 | public static class Builder{ 20 | 21 | private String givenName=""; 22 | private String surName=""; 23 | private int age = 0; 24 | private Gender gender = Gender.FEMALE; 25 | private String eMail = ""; 26 | private String phone = ""; 27 | private String address = ""; 28 | 29 | public Person.Builder givenName(String givenName){ 30 | this.givenName = givenName; 31 | return this; 32 | } 33 | 34 | public Person.Builder surName(String surName){ 35 | this.surName = surName; 36 | return this; 37 | } 38 | 39 | public Person.Builder age (int val){ 40 | age = val; 41 | return this; 42 | } 43 | 44 | public Person.Builder gender(Gender val){ 45 | gender = val; 46 | return this; 47 | } 48 | 49 | public Person.Builder email(String val){ 50 | eMail = val; 51 | return this; 52 | } 53 | 54 | public Person.Builder phoneNumber(String val){ 55 | phone = val; 56 | return this; 57 | } 58 | 59 | public Person.Builder address(String val){ 60 | address = val; 61 | return this; 62 | } 63 | 64 | public Person build(){ 65 | return new Person(this); 66 | } 67 | } 68 | 69 | private Person(){ 70 | super(); 71 | } 72 | 73 | private Person(Person.Builder builder){ 74 | givenName = builder.givenName; 75 | surName = builder.surName; 76 | age = builder.age; 77 | gender = builder.gender; 78 | eMail = builder.eMail; 79 | phone = builder.phone; 80 | address = builder.address; 81 | 82 | } 83 | 84 | public String getGivenName(){ 85 | return givenName; 86 | } 87 | 88 | public String getSurName(){ 89 | return surName; 90 | } 91 | 92 | public int getAge(){ 93 | return age; 94 | } 95 | 96 | public Gender getGender(){ 97 | return gender; 98 | } 99 | 100 | public String getEmail(){ 101 | return eMail; 102 | } 103 | 104 | public String getPhone(){ 105 | return phone; 106 | } 107 | 108 | public String getAddress(){ 109 | return address; 110 | } 111 | 112 | public void print(){ 113 | System.out.println( 114 | "\nName: " + givenName + " " + surName + "\n" + 115 | "Age: " + age + "\n" + 116 | "Gender: " + gender + "\n" + 117 | "eMail: " + eMail + "\n" + 118 | "Phone: " + phone + "\n" + 119 | "Address: " + address + "\n" 120 | ); 121 | } 122 | 123 | public String printCustom(Function f){ 124 | return f.apply(this); 125 | } 126 | 127 | 128 | public void printWesternName(){ 129 | 130 | System.out.println("\nName: " + this.getGivenName() + " " + this.getSurName() + "\n" + 131 | "Age: " + this.getAge() + " " + "Gender: " + this.getGender() + "\n" + 132 | "EMail: " + this.getEmail() + "\n" + 133 | "Phone: " + this.getPhone() + "\n" + 134 | "Address: " + this.getAddress()); 135 | } 136 | 137 | 138 | public void printEasternName(){ 139 | 140 | System.out.println("\nName: " + this.getSurName() + " " + this.getGivenName() + "\n" + 141 | "Age: " + this.getAge() + " " + "Gender: " + this.getGender() + "\n" + 142 | "EMail: " + this.getEmail() + "\n" + 143 | "Phone: " + this.getPhone() + "\n" + 144 | "Address: " + this.getAddress()); 145 | } 146 | 147 | 148 | 149 | @Override 150 | public String toString(){ 151 | return "Name: " + givenName + " " + surName + "\n" + "Age: " + age + " Gender: " + gender + "\n" + "eMail: " + eMail + "\n"; 152 | } 153 | 154 | public static List createShortList(){ 155 | List people = new ArrayList<>(); 156 | 157 | people.add( 158 | new Person.Builder() 159 | .givenName("Bob") 160 | .surName("Baker") 161 | .age(21) 162 | .gender(Gender.MALE) 163 | .email("bob.baker@example.com") 164 | .phoneNumber("201-121-4678") 165 | .address("44 4th St, Smallville, KS 12333") 166 | .build() 167 | ); 168 | 169 | people.add( 170 | new Person.Builder() 171 | .givenName("Jane") 172 | .surName("Doe") 173 | .age(25) 174 | .gender(Gender.FEMALE) 175 | .email("jane.doe@example.com") 176 | .phoneNumber("202-123-4678") 177 | .address("33 3rd St, Smallville, KS 12333") 178 | .build() 179 | ); 180 | 181 | people.add( 182 | new Person.Builder() 183 | .givenName("John") 184 | .surName("Doe") 185 | .age(25) 186 | .gender(Gender.MALE) 187 | .email("john.doe@example.com") 188 | .phoneNumber("202-123-4678") 189 | .address("33 3rd St, Smallville, KS 12333") 190 | .build() 191 | ); 192 | 193 | people.add( 194 | new Person.Builder() 195 | .givenName("James") 196 | .surName("Johnson") 197 | .age(45) 198 | .gender(Gender.MALE) 199 | .email("james.johnson@example.com") 200 | .phoneNumber("333-456-1233") 201 | .address("201 2nd St, New York, NY 12111") 202 | .build() 203 | ); 204 | 205 | people.add( 206 | new Person.Builder() 207 | .givenName("Joe") 208 | .surName("Bailey") 209 | .age(67) 210 | .gender(Gender.MALE) 211 | .email("joebob.bailey@example.com") 212 | .phoneNumber("112-111-1111") 213 | .address("111 1st St, Town, CA 11111") 214 | .build() 215 | ); 216 | 217 | people.add( 218 | new Person.Builder() 219 | .givenName("Phil") 220 | .surName("Smith") 221 | .age(55) 222 | .gender(Gender.MALE) 223 | .email("phil.smith@examp;e.com") 224 | .phoneNumber("222-33-1234") 225 | .address("22 2nd St, New Park, CO 222333") 226 | .build() 227 | ); 228 | 229 | people.add( 230 | new Person.Builder() 231 | .givenName("Betty") 232 | .surName("Jones") 233 | .age(85) 234 | .gender(Gender.FEMALE) 235 | .email("betty.jones@example.com") 236 | .phoneNumber("211-33-1234") 237 | .address("22 4th St, New Park, CO 222333") 238 | .build() 239 | ); 240 | 241 | 242 | return people; 243 | } 244 | 245 | } 246 | -------------------------------------------------------------------------------- /Lesson 1/exercices/RoboCallExample/RoboCallExample/build.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | Builds, tests, and runs the project RoboCallExample. 12 | 13 | 73 | 74 | -------------------------------------------------------------------------------- /Lesson 1/exercices/RoboCallExample/RoboCallExample/manifest.mf: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | X-COMMENT: Main-Class will be added automatically by build 3 | 4 | -------------------------------------------------------------------------------- /Lesson 1/exercices/RoboCallExample/RoboCallExample/nbproject/genfiles.properties: -------------------------------------------------------------------------------- 1 | build.xml.data.CRC32=a1476f0a 2 | build.xml.script.CRC32=d8f1afd2 3 | build.xml.stylesheet.CRC32=8064a381@1.68.1.46 4 | # This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. 5 | # Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. 6 | nbproject/build-impl.xml.data.CRC32=a1476f0a 7 | nbproject/build-impl.xml.script.CRC32=464aef00 8 | nbproject/build-impl.xml.stylesheet.CRC32=5a01deb7@1.68.1.46 9 | -------------------------------------------------------------------------------- /Lesson 1/exercices/RoboCallExample/RoboCallExample/nbproject/private/config.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/Lesson 1/exercices/RoboCallExample/RoboCallExample/nbproject/private/config.properties -------------------------------------------------------------------------------- /Lesson 1/exercices/RoboCallExample/RoboCallExample/nbproject/private/private.properties: -------------------------------------------------------------------------------- 1 | compile.on.save=true 2 | do.depend=false 3 | do.jar=true 4 | javac.debug=true 5 | javadoc.preview=true 6 | user.properties.file=/home/mw119255/.netbeans/7.4/build.properties 7 | -------------------------------------------------------------------------------- /Lesson 1/exercices/RoboCallExample/RoboCallExample/nbproject/private/private.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Lesson 1/exercices/RoboCallExample/RoboCallExample/nbproject/project.properties: -------------------------------------------------------------------------------- 1 | annotation.processing.enabled=true 2 | annotation.processing.enabled.in.editor=false 3 | annotation.processing.processors.list= 4 | annotation.processing.run.all.processors=true 5 | annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output 6 | application.title=RoboCallExample 7 | application.vendor=mw119255 8 | build.classes.dir=${build.dir}/classes 9 | build.classes.excludes=**/*.java,**/*.form 10 | # This directory is removed when the project is cleaned: 11 | build.dir=build 12 | build.generated.dir=${build.dir}/generated 13 | build.generated.sources.dir=${build.dir}/generated-sources 14 | # Only compile against the classpath explicitly listed here: 15 | build.sysclasspath=ignore 16 | build.test.classes.dir=${build.dir}/test/classes 17 | build.test.results.dir=${build.dir}/test/results 18 | # Uncomment to specify the preferred debugger connection transport: 19 | #debug.transport=dt_socket 20 | debug.classpath=\ 21 | ${run.classpath} 22 | debug.test.classpath=\ 23 | ${run.test.classpath} 24 | # This directory is removed when the project is cleaned: 25 | dist.dir=dist 26 | dist.jar=${dist.dir}/RoboCallExample.jar 27 | dist.javadoc.dir=${dist.dir}/javadoc 28 | endorsed.classpath= 29 | excludes= 30 | includes=** 31 | jar.compress=false 32 | javac.classpath= 33 | # Space-separated list of extra javac options 34 | javac.compilerargs= 35 | javac.deprecation=false 36 | javac.processorpath=\ 37 | ${javac.classpath} 38 | javac.source=1.8 39 | javac.target=1.8 40 | javac.test.classpath=\ 41 | ${javac.classpath}:\ 42 | ${build.classes.dir} 43 | javac.test.processorpath=\ 44 | ${javac.test.classpath} 45 | javadoc.additionalparam= 46 | javadoc.author=false 47 | javadoc.encoding=${source.encoding} 48 | javadoc.noindex=false 49 | javadoc.nonavbar=false 50 | javadoc.notree=false 51 | javadoc.private=false 52 | javadoc.splitindex=true 53 | javadoc.use=true 54 | javadoc.version=false 55 | javadoc.windowtitle= 56 | main.class=com.example.lambda.Main 57 | manifest.file=manifest.mf 58 | meta.inf.dir=${src.dir}/META-INF 59 | mkdist.disabled=false 60 | platform.active=JDK_1.8 61 | run.classpath=\ 62 | ${javac.classpath}:\ 63 | ${build.classes.dir} 64 | # Space-separated list of JVM arguments used when running the project. 65 | # You may also define separate properties like run-sys-prop.name=value instead of -Dname=value. 66 | # To set system properties for unit tests define test-sys-prop.name=value: 67 | run.jvmargs= 68 | run.test.classpath=\ 69 | ${javac.test.classpath}:\ 70 | ${build.test.classes.dir} 71 | source.encoding=UTF-8 72 | src.dir=src 73 | test.src.dir=test 74 | -------------------------------------------------------------------------------- /Lesson 1/exercices/RoboCallExample/RoboCallExample/nbproject/project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | org.netbeans.modules.java.j2seproject 4 | 5 | 6 | RoboCallExample 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Lesson 1/exercices/RoboCallExample/RoboCallExample/src/com/example/lambda/Gender.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | /** 4 | * @author MikeW 5 | */ 6 | public enum Gender { MALE, FEMALE } 7 | -------------------------------------------------------------------------------- /Lesson 1/exercices/RoboCallExample/RoboCallExample/src/com/example/lambda/Main.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | /** 4 | * 5 | * @author MikeW 6 | */ 7 | public class Main { 8 | 9 | public static void main(String[] args) { 10 | 11 | RoboCallTest01.main(args); 12 | RoboCallTest02.main(args); 13 | RoboCallTest03.main(args); 14 | RoboCallTest04.main(args); 15 | 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Lesson 1/exercices/RoboCallExample/RoboCallExample/src/com/example/lambda/MyTest.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | /** 4 | * @author MikeW 5 | */ 6 | public interface MyTest { 7 | public boolean test(T t); 8 | } 9 | -------------------------------------------------------------------------------- /Lesson 1/exercices/RoboCallExample/RoboCallExample/src/com/example/lambda/Person.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.function.Function; 6 | 7 | /** 8 | * @author MikeW 9 | */ 10 | public class Person { 11 | private String givenName; 12 | private String surName; 13 | private int age; 14 | private Gender gender; 15 | private String eMail; 16 | private String phone; 17 | private String address; 18 | 19 | public static class Builder{ 20 | 21 | private String givenName=""; 22 | private String surName=""; 23 | private int age = 0; 24 | private Gender gender = Gender.FEMALE; 25 | private String eMail = ""; 26 | private String phone = ""; 27 | private String address = ""; 28 | 29 | public Person.Builder givenName(String givenName){ 30 | this.givenName = givenName; 31 | return this; 32 | } 33 | 34 | public Person.Builder surName(String surName){ 35 | this.surName = surName; 36 | return this; 37 | } 38 | 39 | public Person.Builder age (int val){ 40 | age = val; 41 | return this; 42 | } 43 | 44 | public Person.Builder gender(Gender val){ 45 | gender = val; 46 | return this; 47 | } 48 | 49 | public Person.Builder email(String val){ 50 | eMail = val; 51 | return this; 52 | } 53 | 54 | public Person.Builder phoneNumber(String val){ 55 | phone = val; 56 | return this; 57 | } 58 | 59 | public Person.Builder address(String val){ 60 | address = val; 61 | return this; 62 | } 63 | 64 | public Person build(){ 65 | return new Person(this); 66 | } 67 | } 68 | 69 | private Person(){ 70 | super(); 71 | } 72 | 73 | private Person(Person.Builder builder){ 74 | givenName = builder.givenName; 75 | surName = builder.surName; 76 | age = builder.age; 77 | gender = builder.gender; 78 | eMail = builder.eMail; 79 | phone = builder.phone; 80 | address = builder.address; 81 | 82 | } 83 | 84 | public String getGivenName(){ 85 | return givenName; 86 | } 87 | 88 | public String getSurName(){ 89 | return surName; 90 | } 91 | 92 | public int getAge(){ 93 | return age; 94 | } 95 | 96 | public Gender getGender(){ 97 | return gender; 98 | } 99 | 100 | public String getEmail(){ 101 | return eMail; 102 | } 103 | 104 | public String getPhone(){ 105 | return phone; 106 | } 107 | 108 | public String getAddress(){ 109 | return address; 110 | } 111 | 112 | public void print(){ 113 | System.out.println( 114 | "\nName: " + givenName + " " + surName + "\n" + 115 | "Age: " + age + "\n" + 116 | "Gender: " + gender + "\n" + 117 | "eMail: " + eMail + "\n" + 118 | "Phone: " + phone + "\n" + 119 | "Address: " + address + "\n" 120 | ); 121 | } 122 | 123 | @Override 124 | public String toString(){ 125 | return "Name: " + givenName + " " + surName + "\n" + "Age: " + age + " Gender: " + gender + "\n" + "eMail: " + eMail + "\n"; 126 | } 127 | 128 | public static List createShortList(){ 129 | List people = new ArrayList<>(); 130 | 131 | people.add( 132 | new Person.Builder() 133 | .givenName("Bob") 134 | .surName("Baker") 135 | .age(21) 136 | .gender(Gender.MALE) 137 | .email("bob.baker@example.com") 138 | .phoneNumber("201-121-4678") 139 | .address("44 4th St, Smallville, KS 12333") 140 | .build() 141 | ); 142 | 143 | people.add( 144 | new Person.Builder() 145 | .givenName("Jane") 146 | .surName("Doe") 147 | .age(25) 148 | .gender(Gender.FEMALE) 149 | .email("jane.doe@example.com") 150 | .phoneNumber("202-123-4678") 151 | .address("33 3rd St, Smallville, KS 12333") 152 | .build() 153 | ); 154 | 155 | people.add( 156 | new Person.Builder() 157 | .givenName("John") 158 | .surName("Doe") 159 | .age(25) 160 | .gender(Gender.MALE) 161 | .email("john.doe@example.com") 162 | .phoneNumber("202-123-4678") 163 | .address("33 3rd St, Smallville, KS 12333") 164 | .build() 165 | ); 166 | 167 | people.add( 168 | new Person.Builder() 169 | .givenName("James") 170 | .surName("Johnson") 171 | .age(45) 172 | .gender(Gender.MALE) 173 | .email("james.johnson@example.com") 174 | .phoneNumber("333-456-1233") 175 | .address("201 2nd St, New York, NY 12111") 176 | .build() 177 | ); 178 | 179 | people.add( 180 | new Person.Builder() 181 | .givenName("Joe") 182 | .surName("Bailey") 183 | .age(67) 184 | .gender(Gender.MALE) 185 | .email("joebob.bailey@example.com") 186 | .phoneNumber("112-111-1111") 187 | .address("111 1st St, Town, CA 11111") 188 | .build() 189 | ); 190 | 191 | people.add( 192 | new Person.Builder() 193 | .givenName("Phil") 194 | .surName("Smith") 195 | .age(55) 196 | .gender(Gender.MALE) 197 | .email("phil.smith@examp;e.com") 198 | .phoneNumber("222-33-1234") 199 | .address("22 2nd St, New Park, CO 222333") 200 | .build() 201 | ); 202 | 203 | people.add( 204 | new Person.Builder() 205 | .givenName("Betty") 206 | .surName("Jones") 207 | .age(85) 208 | .gender(Gender.FEMALE) 209 | .email("betty.jones@example.com") 210 | .phoneNumber("211-33-1234") 211 | .address("22 4th St, New Park, CO 222333") 212 | .build() 213 | ); 214 | 215 | 216 | return people; 217 | } 218 | 219 | } 220 | -------------------------------------------------------------------------------- /Lesson 1/exercices/RoboCallExample/RoboCallExample/src/com/example/lambda/Predicate.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | public interface Predicate { 4 | public boolean test(T t); 5 | } 6 | -------------------------------------------------------------------------------- /Lesson 1/exercices/RoboCallExample/RoboCallExample/src/com/example/lambda/RoboCallTest01.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * 7 | * @author MikeW 8 | */ 9 | public class RoboCallTest01 { 10 | 11 | public static void main(String[] args) { 12 | 13 | List pl = Person.createShortList(); 14 | RoboContactMethods robo = new RoboContactMethods(); 15 | 16 | System.out.println("\n==== Test 01 ===="); 17 | System.out.println("\n=== Calling all Drivers ==="); 18 | robo.callDrivers(pl); 19 | 20 | System.out.println("\n=== Emailing all Draftees ==="); 21 | robo.emailDraftees(pl); 22 | 23 | System.out.println("\n=== Mail all Pilots ==="); 24 | robo.mailPilots(pl); 25 | 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Lesson 1/exercices/RoboCallExample/RoboCallExample/src/com/example/lambda/RoboCallTest02.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * 7 | * @author MikeW 8 | */ 9 | public class RoboCallTest02 { 10 | 11 | public static void main(String[] args) { 12 | 13 | List pl = Person.createShortList(); 14 | RoboContactMethods2 robo = new RoboContactMethods2(); 15 | 16 | System.out.println("\n==== Test 02 ===="); 17 | System.out.println("\n=== Calling all Drivers ==="); 18 | robo.callDrivers(pl); 19 | 20 | System.out.println("\n=== Emailing all Draftees ==="); 21 | robo.emailDraftees(pl); 22 | 23 | System.out.println("\n=== Mail all Pilots ==="); 24 | robo.mailPilots(pl); 25 | 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Lesson 1/exercices/RoboCallExample/RoboCallExample/src/com/example/lambda/RoboCallTest03.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * @author MikeW 7 | */ 8 | public class RoboCallTest03 { 9 | 10 | public static void main(String[] args) { 11 | 12 | List pl = Person.createShortList(); 13 | RoboContactAnon robo = new RoboContactAnon(); 14 | 15 | System.out.println("\n==== Test 03 ===="); 16 | System.out.println("\n=== Calling all Drivers ==="); 17 | robo.phoneContacts(pl, 18 | new MyTest(){ 19 | @Override 20 | public boolean test(Person p){ 21 | return p.getAge() >=16; 22 | } 23 | } 24 | ); 25 | 26 | System.out.println("\n=== Emailing all Draftees ==="); 27 | robo.emailContacts(pl, 28 | new MyTest(){ 29 | @Override 30 | public boolean test(Person p){ 31 | return p.getAge() >= 18 && p.getAge() <= 25 && p.getGender() == Gender.MALE; 32 | } 33 | } 34 | ); 35 | 36 | 37 | System.out.println("\n=== Mail all Pilots ==="); 38 | robo.mailContacts(pl, 39 | new MyTest(){ 40 | @Override 41 | public boolean test(Person p){ 42 | return p.getAge() >= 23 && p.getAge() <= 65; 43 | } 44 | } 45 | ); 46 | 47 | 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Lesson 1/exercices/RoboCallExample/RoboCallExample/src/com/example/lambda/RoboCallTest04.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | import java.util.List; 4 | import java.util.function.Predicate; 5 | 6 | /** 7 | * 8 | * @author MikeW 9 | */ 10 | public class RoboCallTest04 { 11 | 12 | public static void main(String[] args){ 13 | 14 | List pl = Person.createShortList(); 15 | RoboContactLambda robo = new RoboContactLambda(); 16 | 17 | // Predicates 18 | Predicate allDrivers = p -> p.getAge() >= 16; 19 | Predicate allDraftees = p -> p.getAge() >= 18 && p.getAge() <= 25 && p.getGender() == Gender.MALE; 20 | Predicate allPilots = p -> p.getAge() >= 23 && p.getAge() <= 65; 21 | 22 | System.out.println("\n==== Test 04 ===="); 23 | System.out.println("\n=== Calling all Drivers ==="); 24 | robo.phoneContacts(pl, allDrivers); 25 | 26 | System.out.println("\n=== Emailing all Draftees ==="); 27 | robo.emailContacts(pl, allDraftees); 28 | 29 | System.out.println("\n=== Mail all Pilots ==="); 30 | robo.mailContacts(pl, allPilots); 31 | 32 | // Mix and match becomes easy 33 | System.out.println("\n=== Mail all Draftees ==="); 34 | robo.mailContacts(pl, allDraftees); 35 | 36 | System.out.println("\n=== Call all Pilots ==="); 37 | robo.phoneContacts(pl, allPilots); 38 | 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Lesson 1/exercices/RoboCallExample/RoboCallExample/src/com/example/lambda/RoboContactAnon.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * 7 | * @author MikeW 8 | */ 9 | public class RoboContactAnon { 10 | 11 | public void phoneContacts(List pl, MyTest aTest){ 12 | for(Person p:pl){ 13 | if (aTest.test(p)){ 14 | roboCall(p); 15 | } 16 | } 17 | } 18 | 19 | public void emailContacts(List pl, MyTest aTest){ 20 | for(Person p:pl){ 21 | if (aTest.test(p)){ 22 | roboEmail(p); 23 | } 24 | } 25 | } 26 | 27 | public void mailContacts(List pl, MyTest aTest){ 28 | for(Person p:pl){ 29 | if (aTest.test(p)){ 30 | roboMail(p); 31 | } 32 | } 33 | } 34 | 35 | public void roboCall(Person p){ 36 | System.out.println("Calling " + p.getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p.getPhone()); 37 | } 38 | 39 | public void roboEmail(Person p){ 40 | System.out.println("EMailing " + p.getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p.getEmail()); 41 | } 42 | 43 | public void roboMail(Person p){ 44 | System.out.println("Mailing " + p.getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p.getAddress()); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /Lesson 1/exercices/RoboCallExample/RoboCallExample/src/com/example/lambda/RoboContactLambda.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | import java.util.List; 4 | import java.util.function.Predicate; 5 | 6 | /** 7 | * 8 | * @author MikeW 9 | */ 10 | public class RoboContactLambda { 11 | public void phoneContacts(List pl, Predicate pred){ 12 | for(Person p:pl){ 13 | if (pred.test(p)){ 14 | roboCall(p); 15 | } 16 | } 17 | } 18 | 19 | public void emailContacts(List pl, Predicate pred){ 20 | for(Person p:pl){ 21 | if (pred.test(p)){ 22 | roboEmail(p); 23 | } 24 | } 25 | } 26 | 27 | public void mailContacts(List pl, Predicate pred){ 28 | for(Person p:pl){ 29 | if (pred.test(p)){ 30 | roboMail(p); 31 | } 32 | } 33 | } 34 | 35 | public void roboCall(Person p){ 36 | System.out.println("Calling " + p.getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p.getPhone()); 37 | } 38 | 39 | public void roboEmail(Person p){ 40 | System.out.println("EMailing " + p.getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p.getEmail()); 41 | } 42 | 43 | public void roboMail(Person p){ 44 | System.out.println("Mailing " + p.getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p.getAddress()); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /Lesson 1/exercices/RoboCallExample/RoboCallExample/src/com/example/lambda/RoboContactMethods.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * 7 | * @author MikeW 8 | */ 9 | public class RoboContactMethods { 10 | 11 | public void callDrivers(List pl){ 12 | for(Person p:pl){ 13 | if (p.getAge() >= 16){ 14 | roboCall(p); 15 | } 16 | } 17 | } 18 | 19 | public void emailDraftees(List pl){ 20 | for(Person p:pl){ 21 | if (p.getAge() >= 18 && p.getAge() <= 25 && p.getGender() == Gender.MALE){ 22 | roboEmail(p); 23 | } 24 | } 25 | } 26 | 27 | public void mailPilots(List pl){ 28 | for(Person p:pl){ 29 | if (p.getAge() >= 23 && p.getAge() <= 65){ 30 | roboMail(p); 31 | } 32 | } 33 | } 34 | 35 | 36 | public void roboCall(Person p){ 37 | System.out.println("Calling " + p.getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p.getPhone()); 38 | } 39 | 40 | public void roboEmail(Person p){ 41 | System.out.println("EMailing " + p.getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p.getEmail()); 42 | } 43 | 44 | public void roboMail(Person p){ 45 | System.out.println("Mailing " + p.getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p.getAddress()); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /Lesson 1/exercices/RoboCallExample/RoboCallExample/src/com/example/lambda/RoboContactMethods2.java: -------------------------------------------------------------------------------- 1 | package com.example.lambda; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * 7 | * @author MikeW 8 | */ 9 | public class RoboContactMethods2 { 10 | 11 | public void callDrivers(List pl){ 12 | for(Person p:pl){ 13 | if (isDriver(p)){ 14 | roboCall(p); 15 | } 16 | } 17 | } 18 | 19 | public void emailDraftees(List pl){ 20 | for(Person p:pl){ 21 | if (isDraftee(p)){ 22 | roboEmail(p); 23 | } 24 | } 25 | } 26 | 27 | public void mailPilots(List pl){ 28 | for(Person p:pl){ 29 | if (isPilot(p)){ 30 | roboMail(p); 31 | } 32 | } 33 | } 34 | 35 | public boolean isDriver(Person p){ 36 | return p.getAge() >= 16; 37 | } 38 | 39 | public boolean isDraftee(Person p){ 40 | return p.getAge() >= 18 && p.getAge() <= 25 && p.getGender() == Gender.MALE; 41 | } 42 | 43 | public boolean isPilot(Person p){ 44 | return p.getAge() >= 23 && p.getAge() <= 65; 45 | } 46 | 47 | public void roboCall(Person p){ 48 | System.out.println("Calling " + p.getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p.getPhone()); 49 | } 50 | 51 | public void roboEmail(Person p){ 52 | System.out.println("EMailing " + p.getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p.getEmail()); 53 | } 54 | 55 | public void roboMail(Person p){ 56 | System.out.println("Mailing " + p.getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p.getAddress()); 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /Lesson 1/homework/Lesson01-HW.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/Lesson 1/homework/Lesson01-HW.pdf -------------------------------------------------------------------------------- /Lesson 1/homework/Lesson1.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 3 | * 4 | * JDK 8 MOOC Lesson 1 homework 5 | */ 6 | package lesson1; 7 | 8 | import java.util.ArrayList; 9 | import java.util.Arrays; 10 | import java.util.List; 11 | import java.util.Map; 12 | import java.util.TreeMap; 13 | 14 | /** 15 | * @author Speakjava (simon.ritter@oracle.com) 16 | */ 17 | public class Lesson1 { 18 | /** 19 | * Run the exercises to ensure we got the right answers 20 | */ 21 | public void runExercises() { 22 | System.out.println("JDK 8 Lambdas and Streams MOOC Lesson 1"); 23 | System.out.println("Running exercise 1 solution..."); 24 | exercise1(); 25 | System.out.println("Running exercise 2 solution..."); 26 | exercise2(); 27 | System.out.println("Running exercise 3 solution..."); 28 | exercise3(); 29 | System.out.println("Running exercise 4 solution..."); 30 | exercise4(); 31 | System.out.println("Running exercise 5 solution..."); 32 | exercise5(); 33 | } 34 | 35 | /** 36 | * All exercises should be completed using Lambda expressions and the new 37 | * methods added to JDK 8 where appropriate. There is no need to use an 38 | * explicit loop in any of the code. Use method references rather than full 39 | * lambda expressions wherever possible. 40 | */ 41 | /** 42 | * Exercise 1 43 | * 44 | * Create a string that consists of the first letter of each word in the list 45 | * of Strings provided. 46 | */ 47 | private void exercise1() { 48 | List list = Arrays.asList( 49 | "alpha", "bravo", "charlie", "delta", "echo", "foxtrot"); 50 | 51 | /* YOUR CODE HERE */ 52 | } 53 | 54 | /** 55 | * Exercise 2 56 | * 57 | * Remove the words that have odd lengths from the list. 58 | */ 59 | private void exercise2() { 60 | List list = new ArrayList<>(Arrays.asList( 61 | "alpha", "bravo", "charlie", "delta", "echo", "foxtrot")); 62 | 63 | /* YOUR CODE HERE */ 64 | } 65 | 66 | /** 67 | * Exercise 3 68 | * 69 | * Replace every word in the list with its upper case equivalent. 70 | */ 71 | private void exercise3() { 72 | List list = new ArrayList<>(Arrays.asList( 73 | "alpha", "bravo", "charlie", "delta", "echo", "foxtrot")); 74 | 75 | /* YOUR CODE HERE */ 76 | } 77 | 78 | /** 79 | * Exercise 4 80 | * 81 | * Convert every key-value pair of the map into a string and append them all 82 | * into a single string, in iteration order. 83 | */ 84 | private void exercise4() { 85 | Map map = new TreeMap<>(); 86 | map.put("c", 3); 87 | map.put("b", 2); 88 | map.put("a", 1); 89 | 90 | /* YOUR CODE HERE */ 91 | } 92 | 93 | /** 94 | * Exercise 5 95 | * 96 | * Create a new thread that prints the numbers from the list. 97 | */ 98 | private void exercise5() { 99 | List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); 100 | 101 | /* YOUR CODE HERE */ 102 | } 103 | 104 | /** 105 | * Main entry point for application 106 | * 107 | * @param args the command line arguments 108 | */ 109 | public static void main(String[] args) { 110 | Lesson1 lesson = new Lesson1(); 111 | lesson.runExercises(); 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /Lesson 1/slides/Lesson-1-1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/Lesson 1/slides/Lesson-1-1.pdf -------------------------------------------------------------------------------- /Lesson 1/slides/Lesson-1-2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/Lesson 1/slides/Lesson-1-2.pdf -------------------------------------------------------------------------------- /Lesson 1/slides/Lesson-1-3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/Lesson 1/slides/Lesson-1-3.pdf -------------------------------------------------------------------------------- /Lesson 1/slides/Lesson-1-4.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/Lesson 1/slides/Lesson-1-4.pdf -------------------------------------------------------------------------------- /Lesson 1/slides/Lesson-1-5.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/Lesson 1/slides/Lesson-1-5.pdf -------------------------------------------------------------------------------- /Lesson 1/slides/Lesson-1-6.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/Lesson 1/slides/Lesson-1-6.pdf -------------------------------------------------------------------------------- /Lesson 1/slides/Lesson-1-7.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/Lesson 1/slides/Lesson-1-7.pdf -------------------------------------------------------------------------------- /Lesson 2/README.adoc: -------------------------------------------------------------------------------- 1 | = Lesson 2: Introduction to the Streams API 2 | 3 | In lesson 2 you will learn how to use the new Streams API to apply functional programming techniques in Java. You will learn to: 4 | 5 | * Use functional programming concepts. 6 | * Define streams and stream pipelines in Java. 7 | * Create object streams and primitive streams. 8 | * Create streams using Java classes. 9 | * Use intermediate operations in a stream pipeline. 10 | * Use terminal operations in a stream pipeline. 11 | * Use the ``Optional`` class to handle null values. 12 | -------------------------------------------------------------------------------- /Lesson 2/homework/Lesson02-HW.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/Lesson 2/homework/Lesson02-HW.pdf -------------------------------------------------------------------------------- /Lesson 2/homework/Lesson2.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 3 | * 4 | * JDK 8 MOOC Lesson 2 homework 5 | */ 6 | package lesson2; 7 | 8 | import java.io.BufferedReader; 9 | import java.io.IOException; 10 | import java.nio.charset.StandardCharsets; 11 | import java.nio.file.Files; 12 | import java.nio.file.Paths; 13 | import java.util.Arrays; 14 | import java.util.List; 15 | import java.util.stream.Collectors; 16 | import java.util.stream.Stream; 17 | 18 | /** 19 | * @author Speakjava (simon.ritter@oracle.com) 20 | */ 21 | public class Lesson2 { 22 | private static final String WORD_REGEXP = "[- .:,]+"; 23 | 24 | /** 25 | * Run the exercises to ensure we got the right answers 26 | * 27 | * @throws java.io.IOException 28 | */ 29 | public void runExercises() throws IOException { 30 | System.out.println("JDK 8 Lambdas and Streams MOOC Lesson 2"); 31 | System.out.println("Running exercise 1 solution..."); 32 | exercise1(); 33 | System.out.println("Running exercise 2 solution..."); 34 | exercise2(); 35 | System.out.println("Running exercise 3 solution..."); 36 | exercise3(); 37 | System.out.println("Running exercise 4 solution..."); 38 | exercise4(); 39 | System.out.println("Running exercise 5 solution..."); 40 | exercise5(); 41 | System.out.println("Running exercise 6 solution..."); 42 | exercise6(); 43 | System.out.println("Running exercise 7 solution..."); 44 | exercise7(); 45 | } 46 | 47 | /** 48 | * Exercise 1 49 | * 50 | * Create a new list with all the strings from original list converted to 51 | * lower case and print them out. 52 | */ 53 | private void exercise1() { 54 | List list = Arrays.asList( 55 | "The", "Quick", "BROWN", "Fox", "Jumped", "Over", "The", "LAZY", "DOG"); 56 | 57 | /* YOUR CODE HERE */ 58 | } 59 | 60 | /** 61 | * Exercise 2 62 | * 63 | * Modify exercise 1 so that the new list only contains strings that have an 64 | * odd length 65 | */ 66 | private void exercise2() { 67 | List list = Arrays.asList( 68 | "The", "Quick", "BROWN", "Fox", "Jumped", "Over", "The", "LAZY", "DOG"); 69 | 70 | /* YOUR CODE HERE */ 71 | } 72 | 73 | /** 74 | * Exercise 3 75 | * 76 | * Join the second, third and forth strings of the list into a single string, 77 | * where each word is separated by a hyphen (-). Print the resulting string. 78 | */ 79 | private void exercise3() { 80 | List list = Arrays.asList( 81 | "The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"); 82 | 83 | /* YOUR CODE HERE */ 84 | } 85 | 86 | /** 87 | * Count the number of lines in the file using the BufferedReader provided 88 | */ 89 | private void exercise4() throws IOException { 90 | try (BufferedReader reader = Files.newBufferedReader( 91 | Paths.get("SonnetI.txt"), StandardCharsets.UTF_8)) { 92 | /* YOUR CODE HERE */ 93 | } 94 | } 95 | 96 | /** 97 | * Using the BufferedReader to access the file, create a list of words with 98 | * no duplicates contained in the file. Print the words. 99 | * 100 | * HINT: A regular expression, WORD_REGEXP, is already defined for your use. 101 | */ 102 | private void exercise5() throws IOException { 103 | try (BufferedReader reader = Files.newBufferedReader( 104 | Paths.get("SonnetI.txt"), StandardCharsets.UTF_8)) { 105 | /* YOUR CODE HERE */ 106 | } 107 | } 108 | 109 | /** 110 | * Using the BufferedReader to access the file create a list of words from 111 | * the file, converted to lower-case and with duplicates removed, which is 112 | * sorted by natural order. Print the contents of the list. 113 | */ 114 | private void exercise6() throws IOException { 115 | try (BufferedReader reader = Files.newBufferedReader( 116 | Paths.get("SonnetI.txt"), StandardCharsets.UTF_8)) { 117 | /* YOUR CODE HERE */ 118 | } 119 | } 120 | 121 | /** 122 | * Modify exercise6 so that the words are sorted by length 123 | */ 124 | private void exercise7() throws IOException { 125 | try (BufferedReader reader = Files.newBufferedReader( 126 | Paths.get("SonnetI.txt"), StandardCharsets.UTF_8)) { 127 | /* YOUR CODE HERE */ 128 | } 129 | } 130 | 131 | /** 132 | * Main entry point for application 133 | * 134 | * @param args the command line arguments 135 | * @throws IOException If file access does not work 136 | */ 137 | public static void main(String[] args) throws IOException { 138 | Lesson2 lesson = new Lesson2(); 139 | lesson.runExercises(); 140 | } 141 | } 142 | 143 | -------------------------------------------------------------------------------- /Lesson 2/homework/hw.txt: -------------------------------------------------------------------------------- 1 | From fairest creatures we desire increase, 2 | That thereby beauty's rose might never die, 3 | But as the riper should by time decease, 4 | His tender heir might bear his memory: 5 | But thou contracted to thine own bright eyes, 6 | Feed'st thy light's flame with self-substantial fuel, 7 | Making a famine where abundance lies, 8 | Thy self thy foe, to thy sweet self too cruel: 9 | Thou that art now the world's fresh ornament, 10 | And only herald to the gaudy spring, 11 | Within thine own bud buriest thy content, 12 | And, tender churl, mak'st waste in niggarding: 13 | Pity the world, or else this glutton be, 14 | To eat the world's due, by the grave and thee. 15 | -------------------------------------------------------------------------------- /Lesson 2/slides/Lesson-2-1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/Lesson 2/slides/Lesson-2-1.pdf -------------------------------------------------------------------------------- /Lesson 2/slides/Lesson-2-2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/Lesson 2/slides/Lesson-2-2.pdf -------------------------------------------------------------------------------- /Lesson 2/slides/Lesson-2-3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/Lesson 2/slides/Lesson-2-3.pdf -------------------------------------------------------------------------------- /Lesson 2/slides/Lesson-2-4.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/Lesson 2/slides/Lesson-2-4.pdf -------------------------------------------------------------------------------- /Lesson 2/slides/Lesson-2-5.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/Lesson 2/slides/Lesson-2-5.pdf -------------------------------------------------------------------------------- /Lesson 2/slides/Lesson-2-6.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/Lesson 2/slides/Lesson-2-6.pdf -------------------------------------------------------------------------------- /Lesson 2/slides/Lesson-2-7.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/Lesson 2/slides/Lesson-2-7.pdf -------------------------------------------------------------------------------- /Lesson 3/README.adoc: -------------------------------------------------------------------------------- 1 | = Lesson 3: Advanced Lambda and Stream Concepts 2 | 3 | In lesson 3 you will learn advance stream concepts like reduction and collection. You will learn to: 4 | 5 | Perform a reduction using streams. 6 | Create and use finite and infinite streams in Java. 7 | Avoid the use of forEach. 8 | Save items from from a stream using the Collectors class and the collect method. 9 | Use parallel stream and also learn when not to. 10 | Use techniques for debugging and troublshooting streams. 11 | -------------------------------------------------------------------------------- /Lesson 3/homework/Lesson03-HW.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/Lesson 3/homework/Lesson03-HW.pdf -------------------------------------------------------------------------------- /Lesson 3/homework/Lesson3-HW.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 3 | * 4 | * JDK 8 MOOC Lesson 3 homework 5 | */ 6 | package lesson3; 7 | 8 | import java.io.IOException; 9 | import java.util.List; 10 | import java.util.function.Supplier; 11 | import java.util.stream.Collectors; 12 | import java.util.stream.IntStream; 13 | import java.util.stream.Stream; 14 | 15 | /** 16 | * @author Simon Ritter (@speakjava) 17 | * @author Stuart Marks 18 | */ 19 | public class Lesson3 { 20 | /* How many times to repeat the test. 5 seems to give reasonable results */ 21 | private static final int RUN_COUNT = 5; 22 | 23 | /** 24 | * Used by the measure method to determine how long a Supplier takes to 25 | * return a result. 26 | * 27 | * @param The type of the result provided by the Supplier 28 | * @param label Description of what's being measured 29 | * @param supplier The Supplier to measure execution time of 30 | * @return 31 | */ 32 | static T measureOneRun(String label, Supplier supplier) { 33 | long startTime = System.nanoTime(); 34 | T result = supplier.get(); 35 | long endTime = System.nanoTime(); 36 | System.out.printf("%s took %dms%n", 37 | label, (endTime - startTime + 500_000L) / 1_000_000L); 38 | return result; 39 | } 40 | 41 | /** 42 | * Repeatedly generate results using a Supplier to eliminate some of the 43 | * issues of running a micro-benchmark. 44 | * 45 | * @param The type of result generated by the Supplier 46 | * @param label Description of what's being measured 47 | * @param supplier The Supplier to measure execution time of 48 | * @return The last execution time of the Supplier code 49 | */ 50 | static T measure(String label, Supplier supplier) { 51 | T result = null; 52 | 53 | for (int i = 0; i < RUN_COUNT; i++) 54 | result = measureOneRun(label, supplier); 55 | 56 | return result; 57 | } 58 | 59 | /** 60 | * Computes the Levenshtein distance between every pair of words in the 61 | * subset, and returns a matrix of distances. This actually computes twice as 62 | * much as it needs to, since for every word a, b it should be the case that 63 | * lev(a,b) == lev(b,a) i.e., Levenshtein distance is commutative. 64 | * 65 | * @param wordList The subset of words whose distances to compute 66 | * @param parallel Whether to run in parallel 67 | * @return Matrix of Levenshtein distances 68 | */ 69 | static int[][] computeLevenshtein(List wordList, boolean parallel) { 70 | final int LIST_SIZE = wordList.size(); 71 | int[][] distances = new int[LIST_SIZE][LIST_SIZE]; 72 | 73 | // YOUR CODE HERE 74 | 75 | return distances; 76 | } 77 | 78 | /** 79 | * Process a list of random strings and return a modified list 80 | * 81 | * @param wordList The subset of words whose distances to compute 82 | * @param parallel Whether to run in parallel 83 | * @return The list processed in whatever way you want 84 | */ 85 | static List processWords(List wordList, boolean parallel) { 86 | // YOUR CODE HERE 87 | 88 | return null; 89 | } 90 | 91 | /** 92 | * Main entry point for application 93 | * 94 | * @param args the command line arguments 95 | * @throws IOException If word file cannot be read 96 | */ 97 | public static void main(String[] args) throws IOException { 98 | RandomWords fullWordList = new RandomWords(); 99 | List wordList = fullWordList.createList(1000); 100 | 101 | measure("Sequential", () -> computeLevenshtein(wordList, false)); 102 | measure("Parallel", () -> computeLevenshtein(wordList, true)); 103 | 104 | // measure("Sequential", () -> processWords(wordList, false)); 105 | // measure("Parallel", () -> processWords(wordList, true)); 106 | } 107 | } -------------------------------------------------------------------------------- /Lesson 3/homework/Levenshtein.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 3 | * 4 | * JDK 8 MOOC Lesson 3 homework 5 | */ 6 | package lesson3; 7 | 8 | import java.util.*; 9 | 10 | /** 11 | * Look at Wikipedia for more detail on calculating Levenshtein distances 12 | * 13 | * https://en.wikipedia.org/wiki/Levenshtein_distance 14 | */ 15 | public class Levenshtein { 16 | /** 17 | * Utility method to return the minimum of three integers 18 | * 19 | * @param i0 The first integer 20 | * @param i1 The second integer 21 | * @param i2 The third integer 22 | * @return The minimum of the three parameters 23 | */ 24 | static int min3(int i0, int i1, int i2) { 25 | return Math.min(i0, Math.min(i1, i2)); 26 | } 27 | 28 | /** 29 | * Compute the Levenshtein distance between Strings stringA and stringB, 30 | * respecting supplementary characters (i.e., surrogate pairs). 31 | * The algorithm is the two-row technique from: 32 | * 33 | * https://en.wikipedia.org/wiki/Levenshtein_distance 34 | * 35 | * which is derived from Hjelmqvist, Sten (26 Mar 2012), Fast, memory 36 | * efficient Levenshtein algorithm: 37 | * 38 | * http://www.codeproject.com/Articles/13525/Fast-memory-efficient-Levenshtein-algorithm 39 | * 40 | * @param stringA the first string, must be non-null 41 | * @param stringB the second string, must be non-null 42 | * @return the Levenshtein distance between the two strings 43 | * @throws NullPointerException if either string is null 44 | */ 45 | static int lev(String stringA, String stringB) { 46 | Objects.requireNonNull(stringA); 47 | Objects.requireNonNull(stringB); 48 | 49 | // handle degenerate cases 50 | if (stringA.equals(stringB)) 51 | return 0; 52 | 53 | if (stringA.length() == 0) 54 | return stringB.length(); 55 | 56 | if (stringB.length() == 0) 57 | return stringA.length(); 58 | 59 | // convert strings to code points, represented as int[] 60 | int[] s = stringA.codePoints().toArray(); 61 | int[] t = stringB.codePoints().toArray(); 62 | 63 | // create work vectors 64 | int[] v0 = new int[t.length + 1]; 65 | int[] v1 = new int[t.length + 1]; 66 | Arrays.setAll(v0, i -> i); 67 | 68 | for (int i = 0; i < s.length; i++) { 69 | // calculate v1 (current row distances) from the previous row v0 70 | // first element of v1 is A[i+1][0] 71 | // edit distance is delete (i+1) chars from s to match empty t 72 | v1[0] = i + 1; 73 | 74 | // use formula to fill in the rest of the row 75 | for (int j = 0; j < t.length; j++) { 76 | int cost = (s[i] == t[j]) ? 0 : 1; 77 | v1[j + 1] = min3(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost); 78 | } 79 | 80 | // copy v1 (current row) to v0 (previous row) for next iteration 81 | Arrays.setAll(v0, j -> v1[j]); 82 | } 83 | 84 | return v1[t.length]; 85 | } 86 | 87 | /** 88 | * Main entry point that can be used to test and demonstrate the values 89 | * created for the distance between pairs of strings 90 | * 91 | * @param args the command line arguments (unused) 92 | */ 93 | public static void main(String[] args) { 94 | System.out.println(lev("kitten", "sitting")); 95 | System.out.println(lev("flaw", "lawn")); 96 | System.out.println(lev("gumbo", "gambol")); 97 | System.out.println(lev("ROBERTMELANSON", "ROBERTOMELANSON")); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /Lesson 3/homework/RandomWords.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 3 | * 4 | * JDK 8 MOOC Lesson 3 homework 5 | */ 6 | package lesson3; 7 | 8 | import java.io.BufferedReader; 9 | import java.io.IOException; 10 | import java.nio.file.Files; 11 | import java.nio.file.Paths; 12 | import java.util.Collections; 13 | import java.util.List; 14 | import java.util.Random; 15 | import java.util.stream.Collectors; 16 | 17 | /** 18 | * Class to generate a list of random words 19 | * 20 | * @author Simon Ritter (@speakjava) 21 | */ 22 | public class RandomWords { 23 | private final List sourceWords; 24 | 25 | /** 26 | * Constructor 27 | * 28 | * @throws IOException If the source words file cannot be read 29 | */ 30 | public RandomWords() throws IOException { 31 | try (BufferedReader reader = Files.newBufferedReader(Paths.get("words"))) { 32 | sourceWords = null; // YOUR CODE HERE 33 | 34 | System.out.println("Loaded " + sourceWords.size() + " words"); 35 | } 36 | } 37 | 38 | /** 39 | * Create a list of a given size containing random words 40 | * 41 | * @param listSize The size of the list to create 42 | * @return The created list 43 | */ 44 | public List createList(int listSize) { 45 | Random rand = new Random(); 46 | List wordList = null; // YOUR CODE HERE 47 | 48 | return wordList; 49 | } 50 | 51 | /** 52 | * Return the list of all source words, which cannot be modified 53 | * 54 | * @return The unmodifiable list of all source words 55 | */ 56 | public List allWords() { 57 | return Collections.unmodifiableList(sourceWords); 58 | } 59 | } -------------------------------------------------------------------------------- /Lesson 3/slides/Lesson-3-1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/Lesson 3/slides/Lesson-3-1.pdf -------------------------------------------------------------------------------- /Lesson 3/slides/Lesson-3-2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/Lesson 3/slides/Lesson-3-2.pdf -------------------------------------------------------------------------------- /Lesson 3/slides/Lesson-3-3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/Lesson 3/slides/Lesson-3-3.pdf -------------------------------------------------------------------------------- /Lesson 3/slides/Lesson-3-4.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/Lesson 3/slides/Lesson-3-4.pdf -------------------------------------------------------------------------------- /Lesson 3/slides/Lesson-3-5.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/Lesson 3/slides/Lesson-3-5.pdf -------------------------------------------------------------------------------- /Lesson 3/slides/Lesson-3-6.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/Lesson 3/slides/Lesson-3-6.pdf -------------------------------------------------------------------------------- /Lesson 3/slides/Lesson-3-7.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/Lesson 3/slides/Lesson-3-7.pdf -------------------------------------------------------------------------------- /README.adoc: -------------------------------------------------------------------------------- 1 | === Content of the Functional Programming in Java with Lambdas and Streams Open Online Course 2 | 3 | All JDK 8 MOOC videos: https://www.youtube.com/playlist?list=PLmZusCzyp9mVGG2TjtzTxTBQhMarIV1Dm[Youtube Play List] 4 | 5 | .the content directories 6 | image::images/route.png[] -------------------------------------------------------------------------------- /images/route.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IstanbulJUG/Java8-MOOC/64a0ba090efc9cba5d8b4ab634393dfcb3bae15d/images/route.png --------------------------------------------------------------------------------