카테고리 없음

14_4 컬렉션프레임웍과 함수형 인터페이스 예제

푸곰주 2022. 3. 29. 11:30
package ex14;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Ex14_4 {

	public static void main(String[] args) {
		ArrayList<Integer> list = new ArrayList<>();
		for(int i=0; i<10; i++)
			list.add(i);      //0부터 9까지 저장
		
		list.forEach(i->System.out.print(i+",")); //Consumer!!, i를 받아 모든요소 출력
		System.out.println();
		
		System.out.println(list);
		//원래는 iterator필요.
		Iterator it = list.iterator();
		while(it.hasNext()){ //hasNext로 확인하고 있으면
			System.out.println(it.next()); //
		}
		
		//람다식으로 한줄로~ 편리하다. list.forEach(i->System.out.print(i+","));
		
		
		System.out.println();
		
		
		//list에서 2또는 3의 배수를 제거한다.
		list.removeIf(x -> x%2==0 || x%3==0);
		System.out.println(list);
		
		list.replaceAll(i->i*10); //list의 각 요소에 10을 곱한다.
		System.out.println(list);
		
		Map<String, String> map = new HashMap<>();
		map.put("1", "1");
		map.put("2", "2");
		map.put("3", "3");
		map.put("4", "4");
		
		
		map.forEach((k,v)-> System.out.print("{"+k+","+v+"}"));

		System.out.println();
		//map 출력하려면?
		
		Iterator it2 = map.entrySet().iterator();
		
		while(it2.hasNext()) {
			System.out.println(it2.next());
		}
		
		System.out.println();
		

	}

}

실행결과

 

0,1,2,3,4,5,6,7,8,9,
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0
1
2
3
4
5
6
7
8
9

[1, 5, 7]
[10, 50, 70]
{1,1}{2,2}{3,3}{4,4}
1=1
2=2
3=3
4=4