编程知识 cdmana.com

New developer friendly features after Java 8

Java8 Then new developer friendly features
In this paper , I'm going to describe it from 8 Since Edition Java above all 、 Features that are most beneficial to developers . Why is there such an idea ? You can go to Web Find many articles on , Each is listed Java New features of version . However , A brief overview of the article is missing since 8 The most important change since the edition . well , But why the Eighth Edition ? It's amazing , It is still Java The most commonly used version . Even though Java17 The published , But all this is worth mentioning . You can Twitter Check out my findings on . As you can see ,46% The above respondents are still in production Java8. by comparison , Only less than 10% Using the Java12 Or later .

Java8 Then new developer friendly features

Of course ,Java8 Introduced a lot of changes , Include Lambda expression . After that , No similar version has such a large set of key features . however , You will find that Java8 Some interesting new features since . I am already in Twitter All the examples are posted on , They are shown graphically below . You can use #AfterJava8 Tag find them .

Java8 Then new developer friendly features

Source code

If you want to try it yourself , You can check my source code at any time . So , You need to clone my GitHub The repository (https://github.com/piomin/sample-java-new-features.git). I am using Maven and Java15 Compile .

Switch expression (JDK 12)

Use switch expressions , You can use arrows to define multiple case labels and return values . This function starts from JDK 12 Start offering . It makes Switch Expressions are easier to access .

public String newMultiSwitch(int day) {        return switch (day) {            case 1, 2, 3, 4, 5 -> "workday";            case 6, 7 -> "weekend";            default -> "invalid";        };    }

For lower than 12 Of Java, The same example is quite complex .

public String oldMultiSwitch(int day) {        switch (day) {            case 1:            case 2:            case 3:            case 4:            case 5:                return "workday";            case 6:            case 7:                return "weekend";            default:                return "invalid";        }    }

Sealed class (JDK 15)

Use Sealed Sealing function , You can limit the use of superclasses . Use new keywords sealed, You can define which other classes or interfaces extend or implement the current class .

public abstract sealed class Pet permits Cat, Dog {}

Allowed subclasses must define modifiers . If you don't want to allow any other extensions , You need to use final keyword .

public final class Cat extends Pet {}

On the other hand , You can open the class to extend . under these circumstances , You should use unsealed modifiers .

public non-sealed class Dog extends Pet {}

Of course , The following visible statements are not allowed .

public final class Tiger extends Pet {}

Text block (JDK 13)

A text block is a multiline string text , It avoids using escape sequences , And automatically format strings in a predictable way . It also allows developers to control the format of strings . since Java13 since , Text blocks are provided as preview functions . They are in three double quotation marks (""") Start . Let's look at creating and formatting JSON How easy news is .

public String getNewPrettyPrintJson() {        return """               {                    "firstName": "Piotr",                    "lastName": "Mińkowski"               }               """;    }

Java13 Previous JSON String creation is quite complex .

public String getOldPrettyPrintJson() {        return "{\n" +               "     \"firstName\": \"Piotr\",\n" +               "     \"lastName\": \"Mińkowski\"\n" +               "}";    }

New options (JDK 9/JDK 10)

since Java9 and Java10 since , There are several alternative useful methods . Two of the most interesting ones are orElseThrow and ifPresentOrElse. Use orElseThrow Method , If there is no value , Throw out NoTouchElementException. otherwise , It will return a value .

public Person getPersonById(Long id) {	Optional<Person> personOpt = repository.findById(id);	return personOpt.orElseThrow();}

Because of that , You can avoid isPresent Method used in if sentence .

public Person getPersonByIdOldWay(Long id) {	Optional<Person> personOpt = repository.findById(id);	if (personOpt.isPresent())		return personOpt.get();	else		throw new NoSuchElementException();}

The second interesting way is ifPresentOrElse. If there is value , It will use this value to perform the given operation . otherwise , It will perform the given null based operation .

public void printPersonById(Long id) {	Optional<Person> personOpt = repository.findById(id);	personOpt.ifPresentOrElse(			System.out::println,			() -> System.out.println("Person not found")	);}

about Java8, We can if-else Used directly for isPresent Method .

public void printPersonByIdOldWay(Long id) {	Optional<Person> personOpt = repository.findById(id);	if (personOpt.isPresent())		System.out.println(personOpt.get());	else		System.out.println("Person not found");}

Assembly plant method (JDK 9)

adopt Java9 A new feature of is called the set factory method , You can easily create immutable sets with predefined data . You only need to use... For specific collection types of Method .

List<String> fruits = List.of("apple", "banana", "orange");Map<Integer, String> numbers = Map.of(1, "one", 2,"two", 3, "three");

stay Java9 Before , You may use collections , But it must be a more complicated way .

public List<String> fruits() {	List<String> fruitsTmp = new ArrayList<>();	fruitsTmp.add("apple");	fruitsTmp.add("banana");	fruitsTmp.add("orange");	return Collections.unmodifiableList(fruitsTmp);}public Map<Integer, String> numbers() {	Map<Integer, String> numbersTmp = new HashMap<>();	numbersTmp.put(1, "one");	numbersTmp.put(2, "two");	numbersTmp.put(3, "three");	return Collections.unmodifiableMap(numbersTmp);}

in addition , Just create from the object table ArrayList, You can use Arrays.asList(…) Method .

public List<String> fruitsFromArray() {	String[] fruitsArray = {"apple", "banana", "orange"};	return Arrays.asList(fruitsArray);}

Records(JDK 14)

about Records Record , You can define immutable 、 Data only classes ( Limited to getter). It automatically creates toStringequals and hashCode Method . actually , You only need to define the fields shown below .

public record Person(String name, int age) {}

Have and record Classes with similar functions contain fields 、 Constructors 、getter as well as toStringequals and hashCode Method implementation .

public class PersonOld {    private final String name;    private final int age;    public PersonOld(String name, int age) {        this.name = name;        this.age = age;    }    public String getName() {        return name;    }    public int getAge() {        return age;    }    @Override    public boolean equals(Object o) {        if (this == o) return true;        if (o == null || getClass() != o.getClass()) return false;        PersonOld personOld = (PersonOld) o;        return age == personOld.age && name.equals(personOld.name);    }    @Override    public int hashCode() {        return Objects.hash(name, age);    }    @Override    public String toString() {        return "PersonOld{" +                "name='" + name + '\'' +                ", age=" + age +                '}';    }}

Private method in interface (JDK 9)

since Java8 since , You can use public default methods in the interface . But only in Java9 after , Because of the private methods in the interface , You can take full advantage of this feature .

public interface ExampleInterface {    private void printMsg(String methodName) {        System.out.println("Calling interface");        System.out.println("Interface method: " + methodName);    }    default void method1() {        printMsg("method1");    }    default void method2() {        printMsg("method2");    }}

Local variable type inference (JDK 10/JDK 11)

because Java10, You can declare a local variable without a type . You just need to define var Keywords, not types . because Java11, You can also associate it with lambda Use expressions together , As shown below .

public String sumOfString() {	BiFunction<String, String, String> func = (var x, var y) -> x + y;	return func.apply("abc", "efg");}

Original address :https://piotrminkowski.com/2021/02/01/new-developer-friendly-features-after-java-8/

版权声明
本文为[Old K's Java blog]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/10/20211002145756171I.html

Scroll to Top