상세 컨텐츠

본문 제목

[Stream] Method references

기록 - 프로그래밍/Java

by wjjun 2020. 7. 22. 08:27

본문

메서드 참조

객체에 대한 참조를 얻고 참조된 객체의 메서드를 사용합니다.
객체 참조는 메서드의 매개변수로 전달됩니다.
메서드 참조는 특정 메서드를 호출하여 사용합니다.

  • 메서드 참조 람다 표현식입니다.
Student<String> student1 = c -> System.out.println(c);
Student<String> stident2 = System.out::println;
Function<Student, String> studentName1 = p -> p.getName();
Function<Student, String> studentName2 = Student::getName;

메서드 참조 4가지 사용 예시

1. Static methods

정적(static) 메서드를 메서드 참조로 사용합니다.

public static int getLength(String s) {
  return s.length();
}
  • ClassName::Method
@Before
public void createList(){
  list = new ArrayList<>();
  list.add("abcd");
  list.add("abcde");
  list.add("abcdefg");
  list.add("a");
}

@Test
public void getLengthNomalMethodRefernce(){
  System.out.println(">>> getLength");
  list.stream()
      .mapToInt(s -> MethodReferenceMain.getLength(s))
      .forEach(System.out::println);
}

@Test
public void getLengthStaticMethodReference(){
  System.out.println(">>> getLength static method reference");
  list.stream()
      .mapToInt(MethodReferenceMain::getLength)
      .forEach(System.out::println);
}

---출력결과---
>>> getLength static method reference
4
5
7
1
>>> getLength nomal method reference
4
5
7
1

2. Instance method of a particular object

특정 객체의 인스턴스 메서드(not static)를 메서드 참조로 사용합니다.

public int getLength(String s) {
  return s.length();
}
  • Reference Variable :: Method Name
@Before
public void TEST_createObject() {
  list = new ArrayList<>();
  list.add("a");
  list.add("bb");
  list.add("ccc");
  list.add("dddd");
}

@Test
public void getLengthNomalMethodRefernce() {
  System.out.println(">>> getLength nomal method reference");
  ParticularObjectInstanceMethod oim = new ParticularObjectInstanceMethod();
  list.stream()
      .mapToInt(s -> oim.getLength(s))
      .forEach(System.out::println);
}

@Test
public void getLengthStaticMethodReference() {
  System.out.println(">>> getLength static method reference");
  ParticularObjectInstanceMethod oim = new ParticularObjectInstanceMethod();
  list.stream()
      .mapToInt(oim::getLength)
      .forEach(System.out::println);
}

3. Arbitary object instance method

클래스 이름을 메서드 참조로 직접 사용합니다.

  • ClassName :: Method Name
public class ArbitaryObjectInstanceMethod {

  private List<Student> list;

  public int getLength(String s){
    return s.length();
  }

  @Before
  public void createObject(){
    list = new ArrayList<>();
    list.add(new Student("Jane", 20));
    list.add(new Student("Jany", 30));
    list.add(new Student("Dean", 40));
    list.add(new Student("Kay", 50));
    list.add(new Student("Henry", 100));
  }

  @Test
  public void arbitaryObjectInstanceMethod(){

    int sum = list.stream()
        .mapToInt(g -> g.getGrade())
        .sum();

    double average = list.stream()
        .mapToInt(Student::getGrade)
        .average()
        .getAsDouble();

    System.out.println(sum);
    System.out.println(average);

  }
}

class Student {

  private String name;
  private int grade;

  public Student(String name, int grade) {
    this.name = name;
    this.grade = grade;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getGrade() {
    return grade;
  }

  public void setGrade(int grade) {
    this.grade = grade;
  }
}

---출력결과---
240
48.0

4. Constructor references

생성자를 참조합니다.
정적 메소드 참조와 동일하지만 이름이 다릅니다.

public class ConstructorReference {

  private List<String> list;

  @Before
  public void createObject(){
    list = new ArrayList<>();
    list.add("Jane");
    list.add("Jany");
    list.add("Dean");
    list.add("Kay");
    list.add("Henry");
  }

  @Test
  public void constructorRef1(){
    list.stream()
        .map(n -> new Tester(n))
        .forEach(System.out::println);
  }

  @Test
  public void constructorRef2(){
    list.stream()
        .map(Tester::new)
        .forEach(System.out::println);
  }

}

class Tester {

  private String name;

  public Tester(String name) {
    this.name = name;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  @Override
  public String toString(){
    return "name : " + name;
  }
}

---출력결과---
name : Jane
name : Jany
name : Dean
name : Kay
name : Henry
name : Jane
name : Jany
name : Dean
name : Kay
name : Henry

'기록 - 프로그래밍 > Java' 카테고리의 다른 글

[Stream] Match method  (0) 2020.07.28
[Stream] slice method  (0) 2020.07.27
[Stream] Optional 클래스  (0) 2020.07.23
[Stream] map() flatMap()  (0) 2020.07.20
Generic 장점과 특징  (0) 2020.06.28

관련글 더보기

댓글 영역