자바 에서 사용 가능:
11265 단어 자바
방법 인용 은 세 가지 로 나 뉘 는데 방법 인용 은 한 쌍 의 짝 퉁 을 통 해: 방법 인용 은 함수 식 인터페이스의 또 다른 쓰기 방식 임 을 나타 낸다.
방법 참조
public final class Integer {public static int parseInt(String s) throws NumberFormatException {return parseInt(s,10);}}
방법 인용 을 통 해 방법의 인용 대 가 를 변수 에 줄 수 있 습 니 다. 대 가 를 통 해 Function 에 줄 수 있 습 니 다. 설명 방법 인용 도 함수 식 인터페이스의 쓰기 방식 입 니 다. Lambda 표현 식 도 함수 식 인터페이스 입 니 다. Lambda 표현 식 은 보통 자신 이 방법 체 를 제공 하 는 데 사용 되 고 방법 은 기 존의 방법 을 직접 참조 합 니 다.
public class User {private String username;private Integer age;public User() {}public User(String username, Integer age) {this.username = username;this.age = age;}@Overridepublic String toString() {return "User{" +"username='" + username + '\'' +", age=" + age +'}';}// Getter&Setter}
public static void main(String[] args) {// ::Functionfun = Integer::parseInt; Integer value = fun.apply("123");System.out.println(value);// ::String content = "Hello JDK8";Functionfunc = content::substring; String result = func.apply(1);System.out.println(result);//BiFunctionbiFunction = User::new; User user = biFunction.apply("mengday", 28);System.out.println(user.toString());// ,sayHello(String::toUpperCase, "hello");}// ,private static void sayHello(Functionfunc, String parameter){ String result = func.apply(parameter);System.out.println(result);}
3: 옵션 선택 가능 값
Google Guava 에는 Optional 이 있 으 며 Swift 언어 에 도 이와 유사 한 문법 이 있 습 니 다. Swift 에 서 는 선택 가능 한 값 을 데이터 형식 으로 사용 하여 위치 와 기본 유형 을 동일 하 게 만 들 고 위치 가 매우 높 습 니 다.
package java.util;import java.util.function.Consumer;import java.util.function.Function;import java.util.function.Predicate;import java.util.function.Supplier;/*** @since 1.8*/public final class Optional{ private static final Optional> EMPTY = new Optional<>();private final T value;private Optional() {this.value = null;}// Optionalpublic staticOptional empty() { @SuppressWarnings("unchecked")Optionalt = (Optional ) EMPTY; return t;}private Optional(T value) {this.value = Objects.requireNonNull(value);}// Optional Optionalpublic staticOptional of(T value) { return new Optional<>(value);}// Optional Optional, , Optionalpublic staticOptional ofNullable(T value) { return value == null ? empty() : of(value);}// Optional , , NoSuchElementException 。public T get() {if (value == null) {throw new NoSuchElementException("No value present");}return value;}// true , falsepublic boolean isPresent() {return value != null;}// , , 。public void ifPresent(Consumer super T> consumer) {if (value != null)consumer.accept(value);}// , , Optional , Optionalpublic Optionalfilter(Predicate super T> predicate) { Objects.requireNonNull(predicate);if (!isPresent())return this;elsereturn predicate.test(value) ? this : empty();}// , , , Optional Optional 。public Optional map(Function super T, ? extends U> mapper) {Objects.requireNonNull(mapper);if (!isPresent())return empty();else {return Optional.ofNullable(mapper.apply(value));}}// , Optional , , Optional 。public Optional flatMap(Function super T, Optional> mapper) {Objects.requireNonNull(mapper);if (!isPresent())return empty();else {return Objects.requireNonNull(mapper.apply(value));}}// , ,public T orElse(T other) {return value != null ? value : other;}public T orElseGet(Supplier extends T> other) {return value != null ? value : other.get();}publicT orElseThrow(Supplier extends X> exceptionSupplier) throws X { if (value != null) {return value;} else {throw exceptionSupplier.get();}}}
of 방법 에 대해 서 는 현재 유행 하 는 것 같 습 니 다. static 방법 을 제공 하 는 것 입 니 다. 방법 이름 은 of 이 고 방법의 반환 값 은 현재 클래스 로 돌아 가 며 구조 함 수 를 개인 private 로 설정 하고 정적 of 방법 으로 구조 함 수 를 대체 합 니 다.
public class User {private String username;private Integer age;private User() {}public static User of() {return new User();}private User(String username, Integer age) {this.username = username;this.age = age;}public static User of(String username, Integer age) {return new User(username, age);}}
Main
public static void main(String[] args) {// Optional Java 8 , Guava , Oracle// Optional , , NullPointerExceptionString msg = "hello";Optionaloptional = Optional.of(msg); // ,boolean present = optional.isPresent();// , ,String value = optional.get();// , elseString hi = optional.orElse("hi");// , Lambdaoptional.ifPresent(opt -> System.out.println(opt));}
저자: 거품 코드 의 작은 이 흑
원본:https://urlify.cn/Qjaaue
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.