ForEach: HashSet, HashMap

·2022년 11월 15일
0

예제)

HashSet에 3명의 학생이름을 저장하고 forEach 메소드를 사용해서 전체이름 출력

HashSet<String> hs = new HashSet<String>();
hs.add("김");
hs.add("이");
hs.add("박");

1. 익명의 내부클래스

Consumer<String> action = new Consumer<String>() {
	@Override
	public void accept(String t) {
		System.out.print(t+" ");
	}
};
	hs.forEach(action);
	System.out.println();

2.람다식

	hs.forEach(t->{System.out.print(t+" ");}); 

HashMap을 이용해서 이름 출력

HashMap에서의 forEach

public void forEach(BiConsumer<? super K,? super V> action)
Interface BiConsumer<T,U>를 구현함. 얘도 역시 함수형 인터페이스임

HashMap<Integer/*key*/,String/*value*/> map = new HashMap<Integer,String>();
map.put(1, "김");
map.put(2, "이");
map.put(3, "박");

1.익명의 내부클래스

BiConsumer<Integer,String> action = new BiCOnsumer<Integer,String>(){
	@Override
	public void accept(Integer t,String u){
		System.out.println("key: "+t+", value: "+u);
	}
};
map.forEach(action);

2.람다식

map.forEach((t,u)->{System.out.println("key: "+t+", value: "+u);});

2-1.실행문장이 하나인 경우 {};도 생략가능

map.forEach((t,u)->System.out.println("key:"+t+", value: "+u));
profile
웹개발입문자

0개의 댓글