티스토리 뷰

Dev/Java

Method Reference

마이스토리 2016. 4. 6. 16:04

Java8 부터 class/object의 메소드를 first-class function 처럼 사용할 수 있다.

즉, 메소드를 파라미터로 넘길 수 있다.


예)

public class MethodReferenceExamples {


public static void main(String[] args) {

Arrays.asList(1,2,3,4,5)

//      .forEach(i -> System.out.println(i));

 .forEach(System.out::println); // method reference

System.out.println(

Arrays.asList(new BigDecimal("10.0"), new BigDecimal("23"), new BigDecimal("5"))

     .stream()

//      .sorted()

//      .sorted((b1,b2) -> b1.compareTo(b2))

//      .sorted(BigDecimalUtil::compare) //static method refer

     .sorted(BigDecimal::compareTo) //instace method refer. 자동으로 b1 의 compareTo 메소드에 b2를 파라미터로 사용

     .collect(toList())

);

String targetString = "c";

System.out.println(

Arrays.asList("a","b","c","d")

   .stream()

//    .anyMatch(x -> x.equals("c"))

//    .anyMatch(targetString::equals)

   .anyMatch("c"::equals)

   

);

}

}


class BigDecimalUtil {

public static int compare(BigDecimal b1, BigDecimal b2){

return b1.compareTo(b2);

}

}


예) Constructor를 Method reference로 활용 예

public class MethodReferenceExamples2Constructor {


public static void main(String[] args) {

//=====================================

//파라미터가 하나인 생성자의 method reference 예

//=====================================

Section s1 = new Section(10);

Function<Integer, Section> sectionFactoryWithLamdaExp = number -> new Section(number);

Section s2 = sectionFactoryWithLamdaExp.apply(10);

Function<Integer, Section> sectionFactoryWithMethodReference = Section::new;

Section s3 = sectionFactoryWithMethodReference.apply(10);

//=====================================

//파라미터가 여러 개인 생성자의 method reference 예. 별도의 FunctionalInterface를 만들어 사용

//=====================================

Item p1 = new Item(1L, "A", new BigDecimal("10.0"));

ItemCreator icmr = Item::new;

Item p2 = icmr.create(1L, "A", new BigDecimal("10.0"));

//=====================================

//generic type을 이용한 동적 type constructor 활용. compile time error check enable

//=====================================

ItemA ia = createItem(1L, "A", new BigDecimal("10.0"), ItemA::new);

ItemB ib = createItem(1L, "B", new BigDecimal("10.0"), ItemB::new);

}

private static <T extends Item> T createItem(Long id, String name, BigDecimal price, ItemCreator<T> ic){

return ic.create(id, name, price);

}


}


@FunctionalInterface

interface ItemCreator<T extends Item>{

T create(long id, String name, BigDecimal price);

}


@AllArgsConstructor

@Data

class Section{

int i;

}


@AllArgsConstructor

@Data

class Item{

long id;

String name;

BigDecimal price;

}


class ItemA extends Item{

public ItemA(Long id, String name, BigDecimal price){

super(id, name, price);

}


@Override

public String toString() {

return "A=" + super.toString();

}

}


class ItemB extends Item{

public ItemB(Long id, String name, BigDecimal price){

super(id, name, price);

}


@Override

public String toString() {

return "B=" + super.toString();

}

}


댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28