예제)
HashSet<String> hs = new HashSet<String>();
hs.add("김");
hs.add("이");
hs.add("박");
Consumer<String> action = new Consumer<String>() {
@Override
public void accept(String t) {
System.out.print(t+" ");
}
};
hs.forEach(action);
System.out.println();
hs.forEach(t->{System.out.print(t+" ");});
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, "박");
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);
map.forEach((t,u)->{System.out.println("key: "+t+", value: "+u);});
map.forEach((t,u)->System.out.println("key:"+t+", value: "+u));