Guest User

java8tutorial1

a guest
Dec 3rd, 2018
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 23.73 KB | None | 0 0
  1.  
  2. ********* file in java 8 ***********
  3. Learn to use Java 8 APIs along with Files.list() and DirectoryStream to list all files present in a directory, including hidden files, recursively.
  4.  
  5. 1. List all files and sub-directories using Files.list()
  6. Files.list() method to list all file names and sub-directories in current directory.
  7.  
  8. Files.list(Paths.get("."))
  9. .forEach(System.out::println);
  10.  
  11. Output:
  12.  
  13. .\filename1.txt
  14. .\directory1
  15. .\filename2.txt
  16. .\Employee.java
  17. 2. List only files inside directory using filter expression
  18. You can use filters to filter out sub-directories and print only file names, if you need it.
  19.  
  20. Files.list(Paths.get("."))
  21. .filter(Files::isRegularFile)
  22. .forEach(System.out::println);
  23.  
  24. Output:
  25.  
  26. .\filename1.txt
  27. .\filename2.txt
  28. .\Employee.java
  29. To list files in a different directory, we can replace "." with the full path of the directory we desire.
  30.  
  31. 3. List files and sub-directories with Files.newDirectoryStream()
  32. Java provides a more flexible way of traversing a directory content using Files.newDirectoryStream().
  33.  
  34. Please note that if we’re working with a large directory, then using DirectoryStream actually make code faster.
  35.  
  36. Files.newDirectoryStream(Paths.get("."))
  37. .forEach(System.out::println);
  38.  
  39. Output:
  40.  
  41. .\filename1.txt
  42. .\directory1
  43. .\filename2.txt
  44. .\Employee.java
  45. 4. List only files with Files.newDirectoryStream()
  46. To list out only files and excluding all directories from stream, use path filter as second argument.
  47.  
  48. Files.newDirectoryStream(Paths.get("."), path -> path.toFile().isFile())
  49. .forEach(System.out::println);
  50.  
  51. Output:
  52.  
  53. .\filename1.txt
  54. .\filename2.txt
  55. .\Employee.java
  56. 5. List files of certain extention with Files.newDirectoryStream()
  57. You can change the path filter expression passed in second argument to get files of certain extension only.
  58.  
  59. Files.newDirectoryStream(Paths.get("."),
  60. path -> path.toString().endsWith(".java"))
  61. .forEach(System.out::println);
  62.  
  63. Output:
  64.  
  65. .\Employee.java
  66. 6. Find all hidden files in directory
  67. To find all hidden files, you can use filter expression file -> file.isHidden() in any of above example.
  68.  
  69. Or you can use this shortcut method.
  70.  
  71. final​ ​File​​[]​ files = ​new​ ​File​(​"."​).listFiles(file -> file.isHidden());
  72. //or
  73. final​ ​File​​[]​ files = ​new​ ​File​(​"."​).listFiles(​File​::isHidden);
  74. In above examples, we learn to use java 8 APIs list or iterate files in directory recursively on various search criteria. Feel free to modify the code and play with it.
  75.  
  76.  
  77.  
  78. ********** write a file **********
  79. Java 8 example to content into file. You may find examples of reading files using java 8 APIs in linked blog post.
  80.  
  81. 1. Java 8 write to file using BufferedWriter
  82. BufferedWriter is used to write text to a character or byte stream. Before printing the characters, it stores the characters in buffer and print in bunches. Without buffering, each invocation of a print() method would cause characters to be converted into bytes that would then be written immediately to the file, which can be very inefficient.
  83.  
  84. Java program to write content to file using Java 8 APIs is –
  85.  
  86. //Get the file reference
  87. Path path = Paths.get("c:/output.txt");
  88.  
  89. //Use try-with-resource to get auto-closeable writer instance
  90. try (BufferedWriter writer = Files.newBufferedWriter(path))
  91. {
  92. writer.write("Hello World !!");
  93. }
  94. 2. Write to file using Files.write()
  95. Using Files.write() method is also pretty much clean code.
  96.  
  97. String content = "Hello World !!";
  98.  
  99. Files.write(Paths.get("c:/output.txt"), content.getBytes());
  100.  
  101.  
  102. ********** String to date **********
  103.  
  104. 1) Convert string to date in ISO8601 format
  105. By default, java dates are in ISO8601 format, so if you have any string which represent date in ISO8601 format then you can use LocalDate.parse() or LocalDateTime.parse() methods directly.
  106.  
  107. String armisticeDate = "2016-04-04";
  108.  
  109. LocalDate aLD = LocalDate.parse(armisticeDate);
  110. System.out.println("Date: " + aLD);
  111.  
  112. String armisticeDateTime = "2016-04-04T11:50";
  113.  
  114. LocalDateTime aLDT = LocalDateTime.parse(armisticeDateTime);
  115. System.out.println("Date/Time: " + aLDT);
  116.  
  117. Output:
  118.  
  119. Date: 2016-04-04
  120. Date/Time: 2016-04-04T11:50
  121. 2) Convert string to date in custom formats
  122. If you have dates in some custom format, then you need to put additional logic to handle formatting as well using DateTimeFormatter.ofPattern().
  123.  
  124.  
  125. String anotherDate = "04 Apr 2016";
  126.  
  127. DateTimeFormatter df = DateTimeFormatter.ofPattern("dd MMM yyyy");
  128. LocalDate random = LocalDate.parse(anotherDate, df);
  129.  
  130. System.out.println(anotherDate + " parses as " + random);
  131.  
  132.  
  133. ********** join array and String **********
  134.  
  135. Java examples to join string array to produce single String. This code can be used to convert array to string in Java. We may need this information many times during development specially while parsing contents out of JSON or XML.
  136.  
  137. 1. Join String Array – Java 8 String.join()
  138. String.join() method has two overloaded forms.
  139.  
  140. Join multiple string arguments
  141. This method takes all strings in var-args format and all strings are passed as argument in the method. The return string is received by appending all strings delimited by argument separator.
  142.  
  143. Method Syntax
  144. String join(CharSequence delimiter, CharSequence... elements)
  145. This method can be used to join multiple strings which are not yet in form of collection or array.
  146.  
  147. String Join Example
  148. String joinedString = String.join(", ", "How", "To", "Do", "In", "Java");
  149. System.out.println(joinedString);
  150.  
  151. Output:
  152.  
  153. How, To, Do, In, Java
  154. Join array or list of strings
  155. Method Syntax
  156. String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
  157. This method is used to join array of strings or list of strings.
  158.  
  159. Java program to join list of strings
  160.  
  161. Java program to join list of strings
  162. List<String> strList = Arrays.asList("How", "To", "Do", "In", "Java");
  163.  
  164. String joinedString = String.join(", ", strList);
  165.  
  166. System.out.println(joinedString);
  167.  
  168. Output:
  169.  
  170. How, To, Do, In, Java
  171. Java program to join array of strings
  172.  
  173. Java program to join array of strings
  174. String[] strArray = { "How", "To", "Do", "In", "Java" };
  175.  
  176. String joinedString = String.join(", ", strArray);
  177.  
  178. System.out.println(joinedString);
  179.  
  180. Output:
  181.  
  182. How, To, Do, In, Java
  183. 2. Java 8 StringJoiner for formatted output
  184. Using StringJoiner class, we can produce formatted output of joined string. This is specially useful while using lambda collectors.
  185.  
  186. 2.1. Method Syntax
  187. It’s constructor takes three arguments – delimiter [mandatory], and optionally prefix and suffix.
  188.  
  189. StringJoiner(CharSequence delimiter)
  190. StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
  191. 2.2. StringJoiner Example
  192. Run the example with similar input as above example to join multiple strings. We want to format the output as [How, To, Do, In, Java], then we can use below code:
  193.  
  194. StringJoiner joiner = new StringJoiner(", ", "[", "]");
  195.  
  196. joiner.add("How")
  197. .add("To")
  198. .add("Do")
  199. .add("In")
  200. .add("Java");
  201.  
  202. Output:
  203.  
  204. [How, To, Do, In, Java]
  205. 3. String list of string with Collectors.joining()
  206. While using Java 8 lambda, we can use Collectors.joining() to convert list to String.
  207.  
  208. List<String> numbers = Arrays.asList("How", "To", "Do", "In", "Java");
  209.  
  210. String joinedString = numbers
  211. .stream()
  212. .collect(Collectors.joining(", ","[","]"));
  213.  
  214. System.out.println(joinedString);
  215.  
  216. Output:
  217.  
  218. [How, To, Do, In, Java]
  219. 4. Join String Array using StringUtils.join()
  220. The StringUtils class of the Commons Langs library has several join() methods that can be used to combine an array or list of strings into a single string.
  221.  
  222. 4.1. Maven Dependency
  223. pom.xml
  224. <dependency>
  225. <groupId>org.apache.commons</groupId>
  226. <artifactId>commons-lang3</artifactId>
  227. <version>3.7</version>
  228. </dependency>
  229. 4.2. StringUtils.join() Example
  230. See given examples. First we are joining string array with empty string. In second example, we are joining array with comma.
  231.  
  232. String[] strArray = { "How", "To", "Do", "In", "Java" };
  233.  
  234. String joinedString = StringUtils.join(strArray);
  235. System.out.println(joinedString);
  236.  
  237. String joinedString2 = StringUtils.join(strArray, ", ");
  238. System.out.println(joinedString2);
  239.  
  240. Output:
  241.  
  242. HowToDoInJava
  243. How, To, Do, In, Java
  244. Use above given examples to concatenate string array with in Java.
  245.  
  246.  
  247. ********** extract arithmetic **********
  248.  
  249.  
  250. Java 8 has brought many awesome features for java developers. Some of them I have already described in Comparator changes, Streams examples, Internal vs. external iterations, predicates, functional interfaces, default methods, lambda expressions and date and time API changes. All above changes were related to lambda expressions, which is the most attention grabber and somehow game changer as well.
  251.  
  252. Apart from above changes, we got non-lambda expression changes as well. I already discussed about String.join() method in previous post. In this post, I am discussing about changes done in Math class to support exact arithmetic.
  253.  
  254. Sections in this post:
  255.  
  256. 1) (add|substract|multiply|increment|decrement|negate)Exact methods
  257. 2) floorMod and floorDiv methods
  258. 3) toIntExact method
  259. 4) nextDown method
  260. Let’s discuss them one by one.
  261.  
  262. 1) (add|substract|multiply|increment|decrement|negate)Exact methods
  263. The Math class provides these new methods which throws "java.lang.ArithmeticException" exception every-time the result of operation overflows to max limit. All above methods takes arguments as either int or long primitives.
  264.  
  265. e.g. Consider multiplication of 100000 * 100000. Normally done, it will give you a wrong return “silently” and in application runtime it’s your responsibility to check every time the max limit to avoid wrong calculations.
  266.  
  267. In java 8, multiPlyExact method will do the job for you and will throw the exception if result overflow the max limit.
  268.  
  269. //Normal multiplication
  270. System.out.println( 100000 * 100000 );
  271.  
  272. //Using multiPlyExact
  273. System.out.println( Math.multiplyExact( 100000 , 100000 ));
  274.  
  275. Output:
  276.  
  277. 1410065408 //Incorrect result
  278. Exception in thread "main" java.lang.ArithmeticException: integer overflow
  279. at java.lang.Math.multiplyExact(Math.java:867)
  280. at java8features.MathematicalFuctions.main(MathematicalFuctions.java:8)
  281. The same thing will happen with other operations as well. e.g. add operation vs. addExact
  282.  
  283. //Normal add operation
  284. System.out.println( Integer.MAX_VALUE + Integer.MAX_VALUE );
  285.  
  286. //Using addExact
  287. System.out.println( Math.addExact( Integer.MAX_VALUE , Integer.MAX_VALUE ));
  288.  
  289. Output:
  290.  
  291. -2 //incorrect result
  292. Exception in thread "main" java.lang.ArithmeticException: integer overflow
  293. at java.lang.Math.addExact(Math.java:790)
  294. at java8features.MathematicalFuctions.main(MathematicalFuctions.java:11)
  295. 2) floorMod and floorDiv methods
  296. Java 8 has worked to solve a very long standing problem of integer remainders. Everybody knows that expression n % 2 is
  297.  
  298. i) 0 : if number is even
  299. ii) 1 : if is odd
  300.  
  301. What if number is negative. Above expression can/cannot return -1. If fact for negative numbers, result is unpredictable to me.
  302.  
  303. System.out.println( 10 % 2 );
  304. System.out.println( 11 % 2 );
  305. System.out.println( -15 % 2 );
  306. System.out.println( -16 % 2 );
  307.  
  308. Output:
  309.  
  310. 0
  311. 1
  312. -1
  313. 0
  314. Now do the above mod operation with exact mathematics came with java 8.
  315.  
  316. System.out.println( Math.floorMod(10 , 2) );
  317. System.out.println( Math.floorMod(11 , 2) );
  318. System.out.println( Math.floorMod(-15 , 2) );
  319. System.out.println( Math.floorMod(-16 , 2) );
  320.  
  321. Output:
  322.  
  323. 0
  324. 1
  325. 1
  326. 0
  327. Similarly another problem can be a getting the position of a hour hand of a clock. Let’s say current time is 10 O’clock. You made adjustment of n hours and now want to get it’s position. Formula is simple:
  328.  
  329. Current Position = (position + adjustment) % 12
  330.  
  331. It will work good if (position + adjustment) is computed to position number. But what if hour hand moved anti-clockwise such that (position + adjustment) becomes negative. Let’s check.
  332.  
  333. System.out.println( (10+3) % 12 );
  334. System.out.println( (5+6) % 12 );
  335. System.out.println( (10-27) % 12 );
  336.  
  337. Output:
  338.  
  339. 1
  340. 11
  341. -5 //This is incorrect
  342. Now use the exact airthmatic method floorMod.
  343.  
  344. System.out.println( Math.floorMod(10+3 , 12) );
  345. System.out.println( Math.floorMod(5+6 , 12) );
  346. System.out.println( Math.floorMod(10-27 , 12) );
  347.  
  348. Output:
  349.  
  350. 1
  351. 11
  352. 7 //This is correct
  353. Similar changes has been done in floorDiv() method.
  354.  
  355. 3) toIntExact method
  356. This method is handy when you are trying to assign a long value to int type variable. Though this situation does not arrive easily but it may be required in some rare cases. Normal long to int conversion with cause incorrect data if long value is more than max int value. toIntExact() method will throw the exception if something like this happened.
  357.  
  358. System.out.println( Long.MAX_VALUE );
  359. System.out.println( (int)Long.MAX_VALUE );
  360. System.out.println( Math.toIntExact(10_00_00_000) );
  361. System.out.println( Math.toIntExact(Long.MAX_VALUE) );
  362.  
  363. Output:
  364.  
  365. 9223372036854775807
  366. -1
  367. 100000000
  368. Exception in thread "main" java.lang.ArithmeticException: integer overflow
  369. at java.lang.Math.toIntExact(Math.java:1011)
  370. at java8features.MathematicalFuctions.main(MathematicalFuctions.java:46)
  371. 4) nextDown method
  372. This is also a noticeable new addition in java 8 kit. This is very helpful when you have a situation where you want to return a number less than n. And the number you computed for returning happens to be exactly n. Then you can use this method to find a number closest to n, still less than n.
  373.  
  374. System.out.println( Math.nextDown(100) );
  375. System.out.println( Math.nextDown(100.365) );
  376.  
  377. Output:
  378.  
  379. 99.99999
  380. 100.36499999999998
  381. Please note that Math.nextUp() already existed since java 6. Only Math.nextDown() is added in java 8.
  382.  
  383.  
  384.  
  385. ************** comparator in lambda ****************
  386.  
  387. Comparator is used when we want to sort a collection of objects which can be compared with each other. This comparison can be done using Comparable interface as well, but it restrict you compare these objects in a single particular way only. If you want to sort this collection, based on multiple criterias/fields, then you have to use Comparator only.
  388.  
  389. Quick Reference:
  390.  
  391. //Compare by Id
  392. Comparator<Employee> compareById_1 = Comparator.comparing(e -> e.getId());
  393.  
  394. Comparator<Employee> compareById_2 = (Employee o1, Employee o2) -> o1.getId().compareTo( o2.getId() );
  395.  
  396. //Compare by firstname
  397. Comparator<Employee> compareByFirstName = Comparator.comparing(e -> e.getFirstName());
  398.  
  399. //how to use comparator
  400. Collections.sort(employees, compareById);
  401. 1) Overview
  402. To demo the concept, I am using class Employee with four attributes. We will use it to understand various use cases.
  403.  
  404. public class Employee {
  405. private Integer id;
  406. private String firstName;
  407. private String lastName;
  408. private Integer age;
  409.  
  410. public Employee(Integer id, String firstName, String lastName, Integer age){
  411. this.id = id;
  412. this.firstName = firstName;
  413. this.lastName = lastName;
  414. this.age = age;
  415. }
  416.  
  417. //Other getter and setter methods
  418.  
  419. @Override
  420. public String toString() {
  421. return "\n["+this.id+","+this.firstName+","+this.lastName+","+this.age+"]";
  422. }
  423. }
  424. Additionally I have written one method which always return a list of Employees in unsorted order.
  425.  
  426. private static List<Employee> getEmployees(){
  427. List<Employee> employees = new ArrayList<>();
  428. employees.add(new Employee(6,"Yash", "Chopra", 25));
  429. employees.add(new Employee(2,"Aman", "Sharma", 28));
  430. employees.add(new Employee(3,"Aakash", "Yaadav", 52));
  431. employees.add(new Employee(5,"David", "Kameron", 19));
  432. employees.add(new Employee(4,"James", "Hedge", 72));
  433. employees.add(new Employee(8,"Balaji", "Subbu", 88));
  434. employees.add(new Employee(7,"Karan", "Johar", 59));
  435. employees.add(new Employee(1,"Lokesh", "Gupta", 32));
  436. employees.add(new Employee(9,"Vishu", "Bissi", 33));
  437. employees.add(new Employee(10,"Lokesh", "Ramachandran", 60));
  438. return employees;
  439. }
  440. 2) Sort by first name
  441. Basic usecase where list of employees will be sorted based on their first name.
  442.  
  443. List<Employee> employees = getEmployees();
  444.  
  445. //Sort all employees by first name
  446. employees.sort(Comparator.comparing(e -> e.getFirstName()));
  447.  
  448. //OR you can use below
  449. employees.sort(Comparator.comparing(Employee::getFirstName));
  450.  
  451. //Let's print the sorted list
  452. System.out.println(employees);
  453.  
  454. Output: //Names are sorted by first name
  455.  
  456. [
  457. [3,Aakash,Yaadav,52],
  458. [2,Aman,Sharma,28],
  459. [8,Balaji,Subbu,88],
  460. [5,David,Kameron,19],
  461. [4,James,Hedge,72],
  462. [7,Karan,Johar,59],
  463. [1,Lokesh,Gupta,32],
  464. [10,Lokesh,Ramachandran,60],
  465. [9,Vishu,Bissi,33],
  466. [6,Yash,Chopra,25]
  467. ]
  468. 3) Sort by first name – ‘reverse order’
  469. What if we want to sort on first name but in revered order. It’s really very easy; use reversed() method.
  470.  
  471. List<Employee> employees = getEmployees();
  472.  
  473. //Sort all employees by first name; And then reversed
  474. Comparator<Employee> comparator = Comparator.comparing(e -> e.getFirstName());
  475. employees.sort(comparator.reversed());
  476.  
  477. //Let's print the sorted list
  478. System.out.println(employees);
  479.  
  480. Output: //Names are sorted by first name
  481.  
  482. [[6,Yash,Chopra,25],
  483. [9,Vishu,Bissi,33],
  484. [1,Lokesh,Gupta,32],
  485. [10,Lokesh,Ramachandran,60],
  486. [7,Karan,Johar,59],
  487. [4,James,Hedge,72],
  488. [5,David,Kameron,19],
  489. [8,Balaji,Subbu,88],
  490. [2,Aman,Sharma,28],
  491. [3,Aakash,Yaadav,52]]
  492. 4) Sort by last name
  493. We can use similar code to sort on last name as well.
  494.  
  495. List<Employee> employees = getEmployees();
  496.  
  497. //Sort all employees by first name
  498. employees.sort(Comparator.comparing(e -> e.getLastName()));
  499.  
  500. //OR you can use below
  501. employees.sort(Comparator.comparing(Employee::getLastName));
  502.  
  503. //Let's print the sorted list
  504. System.out.println(employees);
  505.  
  506. Output: //Names are sorted by first name
  507.  
  508. [[9,Vishu,Bissi,33],
  509. [6,Yash,Chopra,25],
  510. [1,Lokesh,Gupta,32],
  511. [4,James,Hedge,72],
  512. [7,Karan,Johar,59],
  513. [5,David,Kameron,19],
  514. [10,Lokesh,Ramachandran,60],
  515. [2,Aman,Sharma,28],
  516. [8,Balaji,Subbu,88],
  517. [3,Aakash,Yaadav,52]]
  518. 5) Sort on multiple fields – thenComparing()
  519. Here we are sorting list of employees first by their first name, and then sort again the list of last name. Just as we apply sorting on SQL statements. It’s actually a very good feature.
  520.  
  521. Now you don’t need to always use sorting on multiple fields in SQL select statements, you can sort them in java as well.
  522.  
  523. List<Employee> employees = getEmployees();
  524.  
  525. //Sorting on multiple fields; Group by.
  526. Comparator<Employee> groupByComparator = Comparator.comparing(Employee::getFirstName)
  527. .thenComparing(Employee::getLastName);
  528. employees.sort(groupByComparator);
  529.  
  530. System.out.println(employees);
  531.  
  532. Output:
  533.  
  534. [3,Aakash,Yaadav,52],
  535. [2,Aman,Sharma,28],
  536. [8,Balaji,Subbu,88],
  537. [5,David,Kameron,19],
  538. [4,James,Hedge,72],
  539. [7,Karan,Johar,59],
  540. [1,Lokesh,Gupta,32], //These both employees are
  541. [10,Lokesh,Ramachandran,60], //sorted on last name as well
  542. [9,Vishu,Bissi,33],
  543. [6,Yash,Chopra,25]
  544. 5) Parallel sort (with multiple threads)
  545. You can sort the collection of objects in parallel using multiple threads as well. It is going to be very fast if collection is big enough having thousands of objects. For small collection of objects, normal sorting is good enough and recommended.
  546.  
  547. //Parallel Sorting
  548. Employee[] employeesArray = employees.toArray(new Employee[employees.size()]);
  549.  
  550. //Parallel sorting
  551. Arrays.parallelSort(employeesArray, groupByComparator);
  552.  
  553. System.out.println(employeesArray);
  554.  
  555. Output:
  556.  
  557. [3,Aakash,Yaadav,52],
  558. [2,Aman,Sharma,28],
  559. [8,Balaji,Subbu,88],
  560. [5,David,Kameron,19],
  561. [4,James,Hedge,72],
  562. [7,Karan,Johar,59],
  563. [1,Lokesh,Gupta,32], //These both employees are
  564. [10,Lokesh,Ramachandran,60], //sorted on last name as well
  565. [9,Vishu,Bissi,33],
  566. [6,Yash,Chopra,25]
  567. That’s all for using lambda with Comparator to sort objects. Please share with all of us if you know more techniques around this concept.
  568.  
  569. ************* regrax as predicates ************
  570.  
  571. Learn to compile regular expression into java.util.function.Predicate. This can be useful when you want to perform some operation on matched tokens.
  572.  
  573. Convert Regex to Predicate
  574. I have list of emails with different domain and I want to perform some operation only on email ids with domain name “example.com”.
  575.  
  576. Now use Pattern.compile().asPredicate() method to get a predicate from compiled regular expression. This predicate can be used with lambda streams to apply it on each token into stream.
  577.  
  578. import java.util.Arrays;
  579. import java.util.List;
  580. import java.util.function.Predicate;
  581. import java.util.regex.Pattern;
  582. import java.util.stream.Collectors;
  583.  
  584. public class RegexPredicateExample {
  585. public static void main(String[] args) {
  586. // Compile regex as predicate
  587. Predicate<String> emailFilter = Pattern
  588. .compile("^(.+)@example.com$")
  589. .asPredicate();
  590.  
  591. // Input list
  592. List<String> emails = Arrays.asList("alex@example.com", "bob@yahoo.com",
  593. "cat@google.com", "david@example.com");
  594.  
  595. // Apply predicate filter
  596. List<String> desiredEmails = emails
  597. .stream()
  598. .filter(emailFilter)
  599. .collect(Collectors.<String>toList());
  600.  
  601. // Now perform desired operation
  602. desiredEmails.forEach(System.out::println);
  603. }
  604. }
  605. Output:
  606.  
  607. alex@example.com
  608. david@example.com
  609. Using Regex using Pattern.matcher()
  610. If you want to use good old Pattern.matcher(), then use below code template.
  611.  
  612. public static void main(String[] args)
  613. {
  614.  
  615. Pattern pattern = Pattern.compile("^(.+)@example.com$");
  616.  
  617. // Input list
  618. List<String> emails = Arrays.asList("alex@example.com", "bob@yahoo.com",
  619. "cat@google.com", "david@example.com");
  620.  
  621. for(String email : emails)
  622. {
  623. Matcher matcher = pattern.matcher(email);
  624.  
  625. if(matcher.matches())
  626. {
  627. System.out.println(email);
  628. }
  629. }
  630. }
  631. Output:
  632.  
  633. alex@example.com
  634. david@example.com
  635.  
  636. *************** join string *****************
  637.  
  638. SO far till java 7, we had String.split() method which can split a string based on some token passed as parameter. It returned list of string tokens as string array. But, if you want to join a string or create a CSV by concatenating string tokens using some separator between them, you have to iterate through list of Strings, or array of Strings, and then use StringBuilder or StringBuffer object to concatenate those string tokens and finally get the CSV.
  639.  
  640. String concatenation (CSV) with join()
  641. Java 8 made the task easy. Now you have String.join() method where first parameter is separator and then you can pass either multiple strings or some instance of Iterable having instances of strings as second parameter. It will return the CSV in return.
  642.  
  643. package java8features;
  644.  
  645. import java.time.ZoneId;
  646.  
  647. public class StringJoinDemo {
  648. public static void main(String[] args){
  649. String joined = String.join("/","usr","local","bin");
  650. System.out.println(joined);
  651.  
  652. String ids = String.join(", ", ZoneId.getAvailableZoneIds());
  653. System.out.println(ids);
  654. }
  655. }
  656.  
  657. Output:
  658.  
  659. usr/local/bin
  660. Asia/Aden, America/Cuiaba, Etc/GMT+9, Etc/GMT+8.....
  661. So next time you use java 8 and want to concatanate the strings, you have a handy method in your kit. Use it.
Add Comment
Please, Sign In to add comment