forEach: ArrayList 메소드

  • 문법
    public void forEach(Consumer<? super E> action)
  • Consumer

    -> 함수형 인터페이스(FunctionalInterface): 추상메소드를 한개만 가지고 있는 인터페이스
    -> 익명의 내부클래스, 람다식을 사용해볼 수 있겠다.
    -> 추상메소드: accept
    public void accept(String t)
    ArrayList의 요소가 파라미터로 순차적으로 전달됨
  • <? super E>

    제네릭에 들어갈 수 있는 타입이 E타입 또는 E타입의 부모
ArrayList<String> al = new ArrayList<String>();
	al.add("김");
	al.add("이");
	al.add("박");	

1. 익명의 내부클래스

Consumer<String> action = new Consumer<String>() {	
//유일한 추상메소드 오버라이딩
	@Override
	public void accept(String t) { 
		System.out.print(t+" ");
	}
};
al.forEach(action);
System.out.println();

2. 람다식

Consumer<String> action1=(String t)->{
	System.out.print(t+" ");
};
al.forEach(action1);

2-1. 람다식2 action1 자리에 구현부를 바로 넣어줄 수 있음

  • 구현부: (String t)->{System.out.print(t+" ");}
al.forEach((String t)->{
	System.out.print(t+" ");
});

2-2.람다식3 자료형(String) 생략가능

	al.forEach((t)->{
		System.out.println(t);
		});

2.3.람다식4 괄호도 생략가능

al.forEach(t->{System.out.println(t);});

예제

ArrayList에 Person 객체 3개 넣고 forEach메소드 사용해서 출력

1. person 클래스

public class Person {
	private String name;
	private int age;
	
	public Person(String name, int age) {
		super();
		this.name=name;
		this.age=age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}

2. main메소드

ArrayList<Person> ap = new ArrayList<Person>();
		ap.add(new Person("김",28));
		ap.add(new Person("이",27));
		ap.add(new Person("박",34));

2-1. 익명의 내부클래스

ap.forEach(new Consumer<Person>() {
	@Override
	public void accept(Person p) {
		System.out.println(p.getName()+", "+p.getAge());
	}
});

2-2. 람다식

ap.forEach(t->{
System.out.println(t.getName()+", "+t.getAge());
});

※주의)

println 인자로 t를 가져오면 toString 오버라이딩이 안돼서 주소값이 나옴.
Person 클래스에 toString 오버라이딩 하거나 get메소드 가져온다.

profile
웹개발입문자

0개의 댓글