Guest User

Untitled

a guest
Feb 19th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.35 KB | None | 0 0
  1. // Java 8
  2. /*
  3. 1. Lambda Expression
  4. 2. Method References
  5. 3. Default Interface Methods
  6. 4. Static Interface Methods
  7. 5. Functional Interfaces
  8. 6. Stream
  9. */
  10.  
  11. import static java.lang.System.out;
  12. import java.util.Arrays;
  13. import java.util.List;
  14. import java.util.ArrayList;
  15. import java.util.Set;
  16. import java.util.Map;
  17. import java.util.Map.Entry;
  18. import java.util.Collections;
  19. import java.util.Comparator;
  20. import java.util.function.Predicate;
  21. import java.util.stream.Collectors;
  22. import java.util.stream.Stream;
  23. import java.time.LocalDate;
  24. import java.time.Month;
  25.  
  26. // 1. Lambda Expression
  27. class LambdaExpression {
  28. interface Mathematics {
  29. int maths(int x, int y);
  30. }
  31. interface Greetings {
  32. void greeting(String message);
  33. }
  34. int calculation(int x, int y, Mathematics m) {
  35. return m.maths(x, y);
  36. }
  37. public void print() {
  38. out.println("1. Lambda Expression");
  39. // Lambda Expression
  40. Mathematics addition = (int x, int y) -> x + y;
  41. Mathematics subtraction = (x, y) -> x - y;
  42. Mathematics multiplication = (x, y) -> { return x * y; };
  43. Mathematics division = (x, y) -> x / y;
  44. out.println("10 + 5 = " + calculation(10, 5, addition));
  45. out.println("10 - 5 = " + calculation(10, 5, subtraction));
  46. out.println("10 * 5 = " + calculation(10, 5, multiplication));
  47. out.println("10 / 5 = " + calculation(10, 5, division));
  48. // Lambda Expression
  49. Greetings greet1 = (message) -> out.println("Hello " + message);
  50. Greetings greet2 = message -> out.println("What's " + message);
  51. greet1.greeting("World!");
  52. greet2.greeting("up?");
  53. out.println();
  54. List<String> names1 = new ArrayList<String>();
  55. names1.add("Delta");
  56. names1.add("Alpha");
  57. names1.add("Epsilon");
  58. names1.add("Beta");
  59. names1.add("Gamma");
  60. List<String> names2 = new ArrayList<String>();
  61. names2.add("Delta");
  62. names2.add("Alpha");
  63. names2.add("Epsilon");
  64. names2.add("Beta");
  65. names2.add("Gamma");
  66. out.println("Sort using Java 7 syntax:");
  67. sortUsingJava7(names1);
  68. out.println(names1);
  69. out.println("Sort using Java 8 syntax:");
  70. sortUsingJava8(names2);
  71. out.println(names2);
  72. out.println();
  73. }
  74. // Sort using Java 7
  75. private void sortUsingJava7(List<String> names) {
  76. Collections.sort(names, new Comparator<String>() {
  77. @Override
  78. public int compare(String s1, String s2) {
  79. return s1.compareTo(s2);
  80. }
  81. });
  82. }
  83. // Sort using Java 8
  84. private void sortUsingJava8(List<String> names) {
  85. Collections.sort(names, (s1, s2) -> s1.compareTo(s2));
  86. }
  87. }
  88.  
  89. // 2. Method References
  90. interface ReverseFunc {
  91. String func(String str);
  92. }
  93. class StringReverse {
  94. // static String reverse(String str) {
  95. String reverse(String str) {
  96. String result = "";
  97. for(int i = str.length() - 1; i >= 0; i--) {
  98. result += str.charAt(i);
  99. }
  100. return result;
  101. }
  102. }
  103. class MethodReferences {
  104. String stringFunc(ReverseFunc revFunc, String str) {
  105. return revFunc.func(str);
  106. }
  107. public void print() {
  108. out.println("2. Method References");
  109. String str = "Hello World!";
  110. String rstr = "";
  111. StringReverse srev = new StringReverse(); //
  112. // Method References
  113. // rstr = stringFunc(StringRevers::reverse, str);
  114. // Method References
  115. rstr = stringFunc(srev::reverse, str);
  116. out.println(rstr);
  117. out.println();
  118. List<String> names = new ArrayList<String>();
  119. names.add("Delta");
  120. names.add("Alpha");
  121. names.add("Epsilon");
  122. names.add("Beta");
  123. names.add("Gamma");
  124. out.println("Print using forEach");
  125. names.forEach(out::println);
  126. out.println();
  127. }
  128. }
  129.  
  130. // 3. Default Interface Methods
  131. interface DefaultService {
  132. int getNumber();
  133. // Default Method
  134. default String getString() {
  135. return "This is the return from Default Interface Method";
  136. }
  137. }
  138. class DefaultImplementation implements DefaultService {
  139. public int getNumber() {
  140. return 100;
  141. }
  142. }
  143. class DefaultInterfaceMethods {
  144. public void print() {
  145. out.println("3. Default Interface Methods");
  146. DefaultImplementation defimp = new DefaultImplementation();
  147. out.println(defimp.getNumber());
  148. out.println(defimp.getString());
  149. out.println();
  150. }
  151. }
  152.  
  153. // 4. Static Interface Methods
  154. interface StaticService {
  155. int getNumber();
  156. // Static Method In Interface
  157. static String getString() {
  158. return "This is the return from Static Method In Interface";
  159. }
  160. }
  161. class StaticImplementation implements StaticService {
  162. public int getNumber() {
  163. return 100;
  164. }
  165. }
  166. class StaticInterfaceMethods {
  167. public void print() {
  168. out.println("4. Static Interface Methods");
  169. StaticImplementation statimp = new StaticImplementation();
  170. out.println(statimp.getNumber());
  171. out.println(StaticService.getString());
  172. out.println();
  173. }
  174. }
  175.  
  176. // 5. Functional Interfaces
  177. interface FunctionalNumber {
  178. double getNumber();
  179. }
  180. class FunctionalInterfaces {
  181. private static int sum = 0;
  182. public void print() {
  183. out.println("5. Functional Interfaces");
  184. FunctionalNumber number;
  185. number = () -> 123.45D;
  186. out.println("Number: " + number.getNumber());
  187. number = () -> Math.random() * 100;
  188. out.println("Random Number: " + number.getNumber());
  189. // int sum = 100;
  190. List<Integer> listp = new ArrayList<Integer>();
  191. listp.add(555);
  192. listp.add(77);
  193. listp.add(3);
  194. out.println("List");
  195. listp.forEach(out::println);
  196. out.println("Sum");
  197. // listp.forEach(n -> out.printf("%d ", (sum += n)));
  198. listp.forEach(n -> out.printf("%d%n", (sum += n)));
  199. out.println();
  200. List<Integer> lst = Arrays.asList(555, 77, 3);
  201. out.println("forEach printf:");
  202. lst.forEach(i -> out.printf("%d ", i)); // lst.forEach(i -> System.out.printf("%d, ", i));
  203. out.println();
  204. out.println("forEach format:");
  205. lst.forEach(i -> out.format("%d ", i)); // lst.forEach(i -> System.out.format("%d, ", i));
  206. out.println();
  207. out.println("format:");
  208. int i = 123;
  209. int j = 456;
  210. out.format("i = %d, j = %d", i, j);
  211. out.println();
  212. out.println("printf:");
  213. out.printf("i = %d, j = %d", i, j);
  214. out.println("\n");
  215. }
  216. }
  217.  
  218. // Predicate
  219. // Predicate exists from before Java 8
  220. class PredicateInterface {
  221. public void print() {
  222. out.println("Predicate predates Java 8");
  223. List<Integer> lst = Arrays.asList(1, 2, 3, 4, 5);
  224. out.println("Integers");
  225. evaluate(lst, n -> true);
  226. out.println("Odd Integers");
  227. evaluate(lst, n -> n % 2 != 0 );
  228. out.println("Even Integers");
  229. evaluate(lst, n -> n % 2 == 0);
  230. List<Integer> ilst = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
  231. // Predicate<Integer> predicate = n -> true
  232. // n is passed as parameter to test method of Predicate interface
  233. // Test method will always return true no matter what value n has
  234. out.println("Print all numbers:");
  235. // pass n as parameter
  236. eval(ilst, n->true);
  237. // Predicate<Integer> predicate1 = n -> n%2 == 0
  238. // n is passed as parameter to test method of Predicate interface
  239. // Test method will return true if n%2 comes to be zero
  240. out.println("Print even numbers:");
  241. eval(ilst, n-> n%2 == 0 );
  242. // Predicate<Integer> predicate2 = n -> n > 3
  243. // n is passed as parameter to test method of Predicate interface
  244. // Test method will return true if n is greater than 3
  245. out.println("Print numbers greater than 3:");
  246. eval(ilst, n-> n > 3 );
  247. out.println();
  248. }
  249. private void evaluate(List<Integer> lst, Predicate<Integer> pred) {
  250. for(int i: lst) {
  251. if(pred.test(i)) {
  252. out.println(i);
  253. }
  254. }
  255. out.println();
  256. }
  257. private void eval(List<Integer> list, Predicate<Integer> predicate) {
  258. for(Integer n: list) {
  259. if(predicate.test(n)) {
  260. out.println(n + " ");
  261. }
  262. }
  263. }
  264. }
  265.  
  266. // 6. Stream (Java 8)
  267. class UtilStream {
  268. public void print() {
  269. Person per = new Person();
  270. List<Person> personList = per.getPersons();
  271. out.println("Person List");
  272. personList.forEach(p -> out.printf("Id: %d, Name: %s, Gender: %s, Date of birth: %s, Income: %.2f\n", p.getId(), p.getName(), p.getGender().toString(), p.getDob().toString(), p.getIncome()));
  273. out.println();
  274. out.println("Filtering by Stream");
  275. List<Person> listPerson = personList.stream().filter(p -> p.getIncome() > 50000.0d).collect(Collectors.toList());
  276. out.println("Person Income > 50000");
  277. for(Person p : listPerson) {
  278. out.printf("Id: %d, Name: %s, Gender: %s, Date of birth: %s, Income: %.2f\n", p.getId(), p.getName(), p.getGender().toString(), p.getDob().toString(), p.getIncome());
  279. }
  280. out.println();
  281. out.println("Stream Iterating");
  282. out.println("Alphabet");
  283. Stream.iterate(65, x -> x + 1)
  284. .filter(x -> (x < 91 | x > 96))
  285. .limit(52)
  286. .forEach(x -> out.printf("%c ", x));
  287. out.println("\n");
  288. out.println("Filtering and Iterating by Stream");
  289. out.println("Person Income > 50000");
  290. personList.stream().filter(p -> p.getIncome() > 50000.0d).forEach(p -> out.printf("Id: %d, Name: %s, Gender: %s, Date of birth: %s, Income: %.2f\n", p.getId(), p.getName(), p.getGender().toString(), p.getDob().toString(), p.getIncome()));
  291. out.println();
  292. out.println("Stream reduce() Method");
  293. double total = personList.stream()
  294. .map(p -> p.getIncome())
  295. .reduce(0.0d, (x, y) -> x + y);
  296. out.printf("Sum Person Income: %.2f\n", total);
  297. out.println();
  298. out.println("Stream reduce() Method by referring sum method of Double class");
  299. total = personList.stream()
  300. .map(p -> p.getIncome())
  301. .reduce(0.0d, Double::sum);
  302. out.printf("Sum Person Income: %.2f\n", total);
  303. out.println();
  304. out.println("Stream Collectors summingDouble() Method");
  305. total = personList.stream().collect(Collectors.summingDouble(p -> p.getIncome()));
  306. out.printf("Sum Person Income: %.2f\n", total);
  307. out.println();
  308. out.println("Stream Max, Min, and Count");
  309. out.println("Stream max() method");
  310. Person personIncomeMax = personList.stream().max((x, y) -> x.getIncome() > y.getIncome() ? 1: -1).get();
  311. out.printf("Maximum Person Income: %.2f\n", personIncomeMax.getIncome());
  312. out.println();
  313. out.println("Stream min() method");
  314. Person personIncomeMin = personList.stream().min((x, y) -> x.getIncome() > y.getIncome() ? 1: -1).get();
  315. out.printf("Minimum Person Income: %.2f\n", personIncomeMin.getIncome());
  316. out.println();
  317. out.println("Stream count() Method");
  318. long counter = personList.stream().filter(p -> p.getIncome() > 50000.0d).count();
  319. out.printf("Count Person Income > 50000: %d\n", counter);
  320. out.println();
  321. out.println("List Stream To Set");
  322. out.println("Person Set");
  323. personList.stream().collect(Collectors.toSet()) .forEach(p -> out.printf("Id: %d, Name: %s, Gender: %s, Date of birth: %s, Income: %.2f\n", p.getId(), p.getName(), p.getGender().toString(), p.getDob().toString(), p.getIncome()));
  324. out.println();
  325. out.println("List Stream into Map");
  326. Map<Long, Person> personIdMap =
  327. personList.stream().collect(Collectors.toMap(p->p.getId(), p->p));
  328. out.println("Person Id - Map Entry");
  329. for(Entry<Long, Person> mapEntry : personIdMap.entrySet()) {
  330. Long id = mapEntry.getKey();
  331. Person pr = mapEntry.getValue();
  332. out.printf("Id: %d - Id: %d, Name: %s, Gender: %s, Date of birth: %s, Income: %.2f\n", id, pr.getId(), pr.getName(), pr.getGender().toString(), pr.getDob().toString(), pr.getIncome());
  333. }
  334. out.println();
  335. out.println("Person Id - Map");
  336. personList.stream().collect(Collectors.toMap(p->p.getId(), p->p)).forEach((x, y) -> out.printf("Id: %d - Id: %d, Name: %s, Gender: %s, Date of birth: %s, Income: %.2f\n", x, y.getId(), y.getName(), y.getGender().toString(), y.getDob().toString(), y.getIncome()));
  337. out.println();
  338. out.println("Stream Method Reference by referring getIncome method of Person class");
  339. out.println("Person Income List");
  340. personList.stream().map(Person::getIncome).collect(Collectors.toList()).forEach(x -> out.printf("%.2f\n", x));
  341. out.println();
  342. // Note
  343. // Method Reference by referring getPersons method of Person class will Map to List<List<Person>>
  344. out.println("Stream Method Reference by referring getPerson method of Person class");
  345. out.println("Person List ");
  346. personList.stream().map(Person::getPerson).collect(Collectors.toList()) .forEach(p -> out.printf("Id: %d, Name: %s, Gender: %s, Date of birth: %s, Income: %.2f\n", p.getId(), p.getName(), p.getGender().toString(), p.getDob().toString(), p.getIncome()));
  347. out.println();
  348. out.println("Parallel Stream");
  349. String namesParallel = personList.parallelStream().filter(Person::isMale).map(Person::getName).collect(Collectors.joining(", "));
  350. out.println(namesParallel);
  351. out.println();
  352. out.println("Mixed Mode: Serial and Parallel Streams");
  353. String namesMixed = personList.stream().filter(Person::isMale).parallel().map(Person::getName).collect(Collectors.joining(", "));
  354. out.println(namesMixed);
  355. }
  356. }
  357.  
  358. class Person {
  359. public static enum Gender {MALE, FEMALE}
  360. private long id;
  361. private String name;
  362. private Gender gen;
  363. private LocalDate dob;
  364. private double income;
  365. public Person() { }
  366. public Person(long id, String name, Gender gen, LocalDate dob, double income) {
  367. this.id = id;
  368. this.name = name;
  369. this.gen = gen;
  370. this.dob = dob;
  371. this.income = income;
  372. }
  373. public long getId() {
  374. return id;
  375. }
  376. public void setId(long id) {
  377. this.id = id;
  378. }
  379. public String getName() {
  380. return name;
  381. }
  382. public void setName(String name) {
  383. this.name = name;
  384. }
  385. public Gender getGender() {
  386. return gen;
  387. }
  388. public boolean isMale() {
  389. return this.gen == Gender.MALE;
  390. }
  391. public boolean isFemale() {
  392. return this.gen == Gender.FEMALE;
  393. }
  394. public void setGender(Gender gen) {
  395. this.gen = gen;
  396. }
  397. public LocalDate getDob() {
  398. return dob;
  399. }
  400. public void setDob(LocalDate dob) {
  401. this.dob = dob;
  402. }
  403. public double getIncome() {
  404. return income;
  405. }
  406. public void setIncome(double income) {
  407. this.income = income;
  408. }
  409. public Person getPerson() {
  410. Person per = new Person(id, name, gen, dob, income);
  411. return per;
  412. }
  413. public List<Person> getPersons() {
  414. Person arete = new Person(1L, "Arete", Gender.MALE, LocalDate.of(1990, Month.JANUARY, 1), 10000.0d);
  415. Person ersa = new Person(2L, "Ersa", Gender.FEMALE, LocalDate.of(1989, Month.FEBRUARY, 2), 20000.0d);
  416. Person hera = new Person(3L, "Hera", Gender.FEMALE, LocalDate.of(1988, Month.MARCH, 3), 30000.0d);
  417. Person elpis = new Person(4L, "Elpis", Gender.MALE, LocalDate.of(1987, Month.APRIL, 4), 40000.0d);
  418. Person soter = new Person(5L, "Soter", Gender.MALE, LocalDate.of(1986, Month.MAY, 5), 50000.0d);
  419. Person nyx = new Person(6L, "Nyx", Gender.FEMALE,
  420. LocalDate.of(1985, Month.JUNE, 6), 60000.0d);
  421. Person aura = new Person(7L, "Aura", Gender.FEMALE, LocalDate.of(1984, Month.JULY, 7), 70000.0d);
  422. Person selene = new Person(8L, "Selene", Gender.FEMALE,
  423. LocalDate.of(1983, Month.AUGUST, 8), 80000.0d);
  424. Person gelos = new Person(9L, "Gelos", Gender.MALE,
  425. LocalDate.of(1982, Month.SEPTEMBER, 9), 90000.0d);
  426. Person techne = new Person(10L, "Techne", Gender.MALE, LocalDate.of(1981, Month.OCTOBER, 10), 1000000.0d);
  427. List<Person> persons = Arrays.asList(arete, ersa, hera, elpis, soter, nyx, aura, selene, gelos, techne);
  428. return persons;
  429. }
  430. @Override
  431. public String toString() {
  432. String str = String.format("(%d, %s, %s, %s, %.2f)", id, name, gen, dob, income);
  433. return str;
  434. }
  435. }
  436.  
  437. public class Program {
  438. public static void main(String... args) {
  439. LambdaExpression lambExpression = new LambdaExpression();
  440. lambExpression.print();
  441.  
  442. MethodReferences methReferences = new MethodReferences();
  443. methReferences.print();
  444.  
  445. DefaultInterfaceMethods defInterfaceMethods = new DefaultInterfaceMethods();
  446. defInterfaceMethods.print();
  447.  
  448. StaticInterfaceMethods stInterfaceMethods = new StaticInterfaceMethods();
  449. stInterfaceMethods.print();
  450.  
  451. FunctionalInterfaces funcInterfaces = new FunctionalInterfaces();
  452. funcInterfaces.print();
  453.  
  454. PredicateInterface predictInterface = new PredicateInterface();
  455. predictInterface.print();
  456.  
  457. UtilStream utlStream = new UtilStream();
  458. utlStream.print();
  459. }
  460. }
Add Comment
Please, Sign In to add comment