Map

민지킴·2021년 3월 25일
0

Map 구조의 key, value값을 가져오는 방법

일단 설명을 위해 기본 데이터를 아래와 같이 만들어 두겠다

HashMap<String,String> hm = new HashMap<String,String>();

hm.put("111", "aaa");

hm.put("222", "bbb");

위에 선언된 hm객체의 key, value 값을 읽어 올 것이다.

방법1.

Iterator<Map.Entry<String,String>> entries = hm.entrySet().iterator();

while(entries.hasNext()){

Entry<String,String> entry = (Entry<String,String>)entries.next();

System.out.println("key : " + entry.getKey() + " , value : " + entry.getValue());

}

// Iterator를 이용해서 하나씩 돌려가며 key, value 정보를 읽는다


방법2.

for(Map.Entry<String,String> entry : hm.entrySet()){

System.out.println("key : " + entry.getKey() + " , value : " + entry.getValue());

}

방법3.

hm.forEach((k,v) -> System.out.println("key : " + k + ", value : " + v));

// JAVA8부터 지원하는 람다식을 이용하는 방법이다. 함수형 프로그래밍으로 아주 간단히

사용할 수 있다


value를 기준으로 정렬하기

public static void main(String[] args){
		Map<Integer, Double> map = new HashMap<Integer, Double>();
		
		map.put(1, 0.8);
		map.put(2, 0.3);
		map.put(3, 0.6);
		map.put(4, 0.9);
		map.put(5, 0.2);
		
		List<Integer> keySetList = new ArrayList<>(map.keySet());
		
		// 오름차순
		System.out.println("------value 오름차순------");
		Collections.sort(keySetList, (o1, o2) -> (map.get(o1).compareTo(map.get(o2))));
		
		for(Integer key : keySetList) {
			System.out.println("key : " + key + " / " + "value : " + map.get(key));
		}
		
		System.out.println();
		
		// 내림차순
		System.out.println("------value 내림차순------");
		Collections.sort(keySetList, (o1, o2) -> (map.get(o2).compareTo(map.get(o1))));
		for(Integer key : keySetList) {
			System.out.println("key : " + key + " / " + "value : " + map.get(key));
		}
	}
profile
하루하루는 성실하게 인생 전체는 되는대로

0개의 댓글