In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "detailed explanation of the New Features of JDK8". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1. Lambda evolution @ Data@ToString@NoArgsConstructor@AllArgsConstructorpublic class Student {/ / name private String name; / / gender private String sex; / / salary private int salary; / / age private int age; / / constellation private String star;} 1.1, general screening
Traversing this set and then judging it in turn is the most common way.
@ Testpublic void test1 () {/ / first create a List list = Arrays.asList (new Student ("Nine days", "male", 5000Power18, "Libra"), new Student ("Ten Nights", "male", 4000Power16, "Pisces"), new Student ("Yoshiro", "male", 3000Men24, "Aquarius"); List result = new ArrayList () For (Student student:list) {if (Libra .equals (student.getStar () {result.add (student);}} System.out.println (result);} 1.2.Anonymous internal class filtering
Filter by adding a judgment condition to the inner class through the method of the anonymous inner class, and first create a public interface:
Public interface FilterProcess {boolean process (T t);}
Then, through a common function, we make a common method for the set and screening conditions to screen the students whose constellations are Libra in the class.
Public List filterStudent (List students, FilterProcess mp) {List list = new ArrayList (); for (Student student: students) {if (mp.process (student)) {list.add (student);}} return list;}
Finally, the result is obtained through the anonymous inner class and the method:
@ Testpublic void test2 () {List students = Arrays.asList (new Student ("Nine days", "male", 5000 men18, "Libra"), new Student ("Ten Nights", "male", 4000 Magi 16, "Pisces"), new Student ("Yoshiro", "male", 3000 Magi 24, "Aquarius")) List list = filterStudent (students, new FilterProcess () {@ Override public boolean process (Student student) {return student.getStar () .equals (Libra);}}); for (Student student: list) {System.out.println (student);}}
The result is shown in the figure:
1.3.semi-Lambda method
But there is a lot of code through both types of code, so java8 provides maximum deletion of code for collection filtering at this point, which is the third method. The third method: direct judgment through Lambda, one step at a time, there is no need to write other methods.
@ Testpublic void test3 () {List list = Arrays.asList (new Student ("Nine days", "male", 5000heli18, "Libra"), new Student ("Ten Nights", "male", 4000Men16, "Pisces"), new Student ("Shiichiro", "male", 3000Men24, "Aquarius"); List result = filterStudent (list, (e)-> e.getStar (). Equals (Libra)) System.out.println (result);}
Test results:
[Student (name= nine days, sex= male, salary=5000, age=18, star= Libra)]
But now someone will ask this question, and it's like this in my method.
FilterStudent (List students, FilterProcess mp)
Why do my code parameters look like this?
FilterStudent (list, (e)-> e.getStar (). Equals (Libra)
In fact,-> this is a connector, the left represents the parameter, and the right represents the function body (that is, the condition we call), this e represents the parameter FilterProcess mp, but the lambda in java8 can attach a condition to this parameter, and these condition filters are encapsulated into the internal class in jdk8 to achieve their own implementation, so we only need to attach conditions, and that (e) represents passing the parameter.
1.4.True use of lambda method @ Testpublic void test1 () {List list = Arrays.asList (new Student ("Nine days", "male", 5000 men18, "Libra"), new Student ("Ten Nights", "male", 4000Power16, "Pisces"), new Student ("Yoshiro", "male", 3000Men24, "Aquarius") List.stream (). Filter ((e)-> e.getStar (). Equals (Libra)) .forEach (System.out::println);}
The result is still the same answer, until the fourth method comes out, compared with the first three methods, it is much simpler, this is the process of our lambda exercise.
Summary: lambda is mainly about filtering conditions in a collection, including arrays, and so on. Next, let's introduce Stream API, which is closely related to Lambda. In terms of importance, lambda is only the foundation, and Stream API is the real upgrade.
2. Detailed explanation of StreamAPI
2.0, featur
Parent class: BasicStream
Subclasses: Stream, IntStream, LongStream, DoubleStream
Contains two types, intermediate operation (intermediate operations) and end operation (terminal operations)
Here are the methods of all the methods that belong to which end of the operation:
Then prepare a test class, and a static variable, below:
Public class JdkTest {public static List list = Arrays.asList (new Student (Nine days, male, 5000, 18, Libra), new Student (Ten Nights, male, 4000, 16, Pisces), new Student (Shiichiro, male, 3000, 24, Aquarius);}
Next, let's analyze their role one by one.
2.1 、 stream
When a collection is converted to a stream, the stream is generally used to continue the subsequent operation.
@ Testpublic void test0 () {list.stream ();} 2.2, forEach traversal
ForEach traverses the collection, and System.out::println is equivalent to System.out.println ()
@ Testpublic void test1 () {list.forEach (System.out::println);}
The result is:
2.3.The filter filter
There is a filter condition in this method, which is equivalent to the filter after the where of the sql query.
@ Testpublic void test2 () {list.stream () .filter ((e)-> e.getStar () .equals) .forEach (System.out::println);}
2.4.The map transform set
Convert List to List, and collect converts the result to List
@ Testpublic void test3 () {List names = list.stream () .map (Student::getName) .requests (Collectors.toList ()); names.stream () .forEach (System.out::println);}
Results:
2.5.The mapToInt conversion numerical stream
Convert the numerical stream, which is equivalent to mapToLong and mapToDouble. The following is the maximum value.
@ Testpublic void test4 () {IntStream intStream = list.stream () .mapToInt (Student::getAge); Stream integerStream = intStream.boxed (); Optional max = integerStream.max (Integer::compareTo); System.out.println (max.get ());}
The result is:
242.6, flatMap merged into one stream
Map each element T in the flow to a stream, and then connect each stream to a stream.
@ Testpublic void test5 () {List list2 = new ArrayList (); list2.add ("aaa bbb ccc"); list2.add ("ddd eee fff"); list2.add ("ggg hhh iii"); list2 = list2.stream () .map (s-> s.split (")) .flatMap (Arrays::stream) .flat (Collectors.toList ()); System.out.println (list2);}
The result is:
[aaa, bbb, ccc, ddd, eee, fff, ggg, hhh, iii] 2.7, distinct deduplicates @ Testpublic void test6 () {List list2 = new ArrayList (); list2.add ("aaa bbb ccc"); list2.add ("ddd eee fff"); list2.add ("ggg hhh iii"); list2.add ("ggg hhh iii"); list2.stream (). Distinct (). ForEach (System.out::println);}
Results:
Aaa bbb cccddd eee fffggg hhh iii2.8, sorted sort @ Testpublic void test7 () {/ / asc sort list.stream () .sorted (Comparator.comparingInt (Student::getAge)) .forEach (System.out::println) System.out.println ("-"); / / desc sort list.stream (). Sorted (Comparator.comparingInt (Student::getAge). Reversed ()) .forEach (System.out::println);}
Results:
Student (name=, sex=, salary=4000, age=16, star= Pisces) Student (name=, sex=, salary=5000, age=18, star= Libra) Student (name=, sex=, salary=3000, age=24, star= Aquarius)-Student (name=, sex=) Salary=3000, age=24, star= Aquarius) Student (name= 9 days, sex= male, salary=5000, age=18, star= Libra) Student (name= Ten Nights, sex= male, salary=4000, age=16, star= Pisces) 2.9, skip skip the first n @ Testpublic void test8 () {list.stream (). Skip (1) .forEach (System.out::println) 2.10. Limit intercepts the first n @ Testpublic void test10 () {list.stream () .limit (1) .forEach (System.out::println);}
The result is:
Student (name= 9 days, sex= male, salary=5000, age=18, star= Libra) 2.11, anyMatch
As long as any one of them meets the criteria
@ Testpublic void test11 () {boolean isHave = list.stream () .anyMatch (student-> student.getAge () = = 16); System.out.println (isHave);} 2.12, allMatch
All match
@ Testpublic void test12 () {boolean isHave = list.stream () .allMatch (student-> student.getAge () = = 16); System.out.println (isHave);} 2.13, noneMatch
Whether it is satisfied or not.
@ Testpublic void test13 () {boolean isHave = list.stream () .noneMatch (student-> student.getAge () = = 16); System.out.println (isHave);} 2.14, findAny
Find one of the elements (the first element is found when using stream (), and one of the elements is found when using parallelStream () parallelism)
@ Testpublic void test14 () {Optional student = list.stream () .findAny (); System.out.println (student.get ());} 2.15, findFirst
Find the first element
@ Testpublic void test15 () {Optional student = list.stream () .findFirst (); System.out.println (student.get ());}
2.17, count count
@ Testpublic void test17 () {long count = list.stream () .count (); System.out.println (count);} 2.18, of
Generate a string stream
@ Testpublic void test18 () {Stream stringStream = Stream.of ("I", "love", "you");} 2.19, empty
Generate an empty stream
@ Testpublic void test19 () {Stream stringStream = Stream.empty ()} 2.20, iterate@Testpublic void test20 () {List list = Arrays.asList ("a", "b", "c", "c", "d", "f", "a") Stream.iterate (0, I-> I + 1) .limit (list.size ()) .forEach (I-> {System.out.println (String.valueOf (I) + list.get (I));}) 3. Date3.1, JDK7 Date shortcomings 1, all date classes are mutable, so they are not thread safe, which is one of the biggest problems of Java date class. 2. The definition of Java date / time class is inconsistent. There are date classes in both java.util and java.sql packages. In addition, the classes used for formatting and parsing are defined in java.text package 3. Java.util.Date contains both date and time. While java.sql.Date contains only dates, it is not reasonable to include them in the java.sql package. In addition, both classes have the same name, which in itself is a very bad design. There are no clearly defined classes for time, timestamp, formatting, and parsing. For formatting and parsing requirements, we have java.text.DateFormat abstract classes, but in general, SimpleDateFormat classes are used for this type of requirements 4. Date classes do not provide internationalization and no time zone support, so Java introduces java.util.Calendar and java.util.TimeZone classes, but they also have all the above problems 3.2, JDK8 Date advantages 1, immutability: in the new date / time API, all classes are immutable This is good for multithreaded environments. 2. Separation of concerns: the new API clearly separates human-readable date time from machine time (unix timestamp), defining different classes for date (Date), time (Time), date time (DateTime), time stamp (unix timestamp), and time zone. 3. Clarity: in all classes, methods are clearly defined to accomplish the same behavior. For example, to get the current instance, we can use the now () method, with format () and parse () methods defined in all classes, instead of having a separate class as before. To better handle the problem, all classes use factory and policy patterns, and once you use the methods of one of these classes, it is not difficult to work with other classes. 4, practical operation: all new date / time API classes implement a series of methods to complete common tasks, such as: add, subtract, format, parse, extract separate parts from date / time, and so on. 5. Scalability: the new date / time API works on the ISO-8601 calendar system, but we can also apply it to non-IOS calendars. 3.3.The new fields for JDK8 Date
What's in the Java.time package is that classes are immutable and thread-safe. The new time and date API is located in java.time, which is interpreted in the key fields under the java8 time package.
Attribute meaning Instant represents a time stamp LocalDate represents a date, for example, 2020-01-14LocalTime represents a time, for example, 12:59:59LocalDateTime represents a specific time 2020-01-12 12:22:26ZonedDateTime represents a complete date time including time zone, offset is Period based on UTC/ Greenwich mean time segment ZoneOffset represents time zone offset, for example: + 8:00Clock represents clock For example, get the current time in New York, USA, Instant instant, get the current time, Instant instant = time () / / get the current timestamp LocalDate localDate = LocalDate.now (); / / get the current date LocalTime localTime = LocalTime.now (); / / get the current time LocalDateTime localDateTime = LocalDateTime.now (); / / get the current specific time ZonedDateTime zonedDateTime = ZonedDateTime.now (); / / get the time 3.5 with time zone, string conversion jdk8:String str = "2019-01-11"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern ("yyyy-MM-dd") LocalDate localDate = LocalDate.parse (str, formatter); jdk7:SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("yyyy-MM-dd"); try {Date date = simpleDateFormat.parse (str);} catch (ParseException e) {e.printStackTrace ();} 3.6.Date conversion LocalDateimport java.time.Instant;import java.time.LocalDate;import java.time.ZoneId;import java.util.Date;public class Test {public static void main (String [] args) {Date date = new Date () The Instant instant = date.toInstant (); ZoneId zoneId = ZoneId.systemDefault (); / / atZone () method returns the ZonedDateTime generated from this Instant in the specified time zone. LocalDate localDate = instant.atZone (zoneId). ToLocalDate (); System.out.println ("Date =" + date); System.out.println ("LocalDate =" + localDate);} 3.7, LocalDate to Dateimport java.time.LocalDate;import java.time.ZoneId;import java.time.ZonedDateTime;import java.util.Date;public class Test {public static void main (String [] args) {ZoneId zoneId = ZoneId.systemDefault (); LocalDate localDate = LocalDate.now () ZonedDateTime zdt = localDate.atStartOfDay (zoneId); Date date = Date.from (zdt.toInstant ()); System.out.println ("LocalDate =" + localDate); System.out.println ("Date =" + date);} 3.8, timestamp to LocalDateTimelong timestamp = System.currentTimeMillis (); Instant instant = Instant.ofEpochMilli (timestamp); LocalDateTime.ofInstant (instant, ZoneId.systemDefault ()); 3.9. LocalDateTime to timestamp LocalDateTime dateTime = LocalDateTime.now () DateTime.toInstant (ZoneOffset.ofHours (8)) .toEpochMilli (); dateTime.toInstant (ZoneOffset.of ("+ 08:00")) .toEpochMilli (); dateTime.atZone (ZoneId.systemDefault ()) .toInstant () .toEpochMilli () 3.10 、 LocalDate method summarizes getYear () int gets the year of the current date getMonth () Month gets the month object of the current date getMonthValue () int gets the month of the current date getDayOfWeek () DayOfWeek indicates the day of the week represented by the object GetDayOfMonth () int means that the date represented by the object is the day of this month. GetDayOfYear () int means that the date represented by the object is the date of this year. WithYear (int year) LocalDate modifies the year of the current object withMonth (int month) LocalDate modifies the month of the current object withDayOfMonth (intdayOfMonth) LocalDate modifies whether the date of the current object in the month isLeapYear () boolean is a leap year lengthOfMonth () int how many days are there in this month lengthOfYear () int the number of days in the year represented by the object (365or 366) plusYears (longyearsToAdd) LocalDate the current object increases the specified number of years plusMonths (longmonthsToAdd) LocalDate current object increases specified number of months plusWeeks (longweeksToAdd) LocalDate current object increases specified number of weeks plusDays (longdaysToAdd) LocalDate current object increases specified number of days minusYears (longyearsToSubtract) LocalDate current object subtracts specified number of years minusMonths (longmonthsToSubtract) LocalDate current object subtracts predetermined number of months minusWeeks (longweeksToSubtract) LocalDate current object minus specified number of weeks minusDays (longdaysToSubtract) LocalDate current object minus the specified number of days compareTo (ChronoLocalDateother) int compares the time size of the current object and the other object If the return value is positive, the current object time is later. IsBefore (ChronoLocalDateother) boolean compares whether the current object date is before the other object date. IsAfter (ChronoLocalDateother) boolean compares whether the current object date is after the other object date. IsEqual (ChronoLocalDateother) boolean compares whether the two date objects are equal. This is the end of the "detailed description of the new features of JDK8". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.