개발자 미니민의 개발스터디

[JAVA] 자바 - Map (HashMap) / TreeMap

by mini_min

[JAVA]
자바 - Map (HashMap)

✔️ Map (HashMap)

인터페이스 구현 클래스.

- 키를 값에 매핑하는 객체 

- 키 중복을 허용하지 않다.

- 1키 1값 저장

- 동작과 성능은 Set 인터페이스와 유사하다.

- 동시성을 지원하는 경우가 있어, 판단해야한다.

 

 

⭕ 키, 값 저장 : put()

//<키, 값>
		Map<String, Integer> map = new HashMap<>();
		
		//map에 값 저장(키,값)
		map.put("서울", 1000);
		map.put("부산", 350);
		map.put("대구", 250);
		map.put("인천", 300);
		map.put("광주", 150);
		map.put("대전", 150);
		map.put("울산", 110);
		map.put("세종", 20);
		map.put("서울", 950);	 //키가 같으므로 기존 값을 덮어쓴다.

 

 

◾ map 에서 키의 값 가져오기

//map에서 키의 값 가져오기
	int n = map.get("서울");		//서울에 저장된 값 가져오기. 
	System.out.println("서울:" + n);
	//map에는 Iterator 이 없으며, 향상된 for문도 사용 불가하다.
💡 map 에서는 반복자가 없다!
향상된 for 문도 사용 불가하다!

 

 

◾ map 의 키에서 Set 객체를 얻어, 키에 대한 Set 객체로 처음부터 끝까지 순회할 수 있다.

Set<String> set = map.keySet();
//키에 대한 Set 객체 생성

Iterator<String> it = set.iterator();
//Set 은 Iterator 가능. 키에 대한 반복자.
while(it.hasNext()) {
	String key = it.next();
    Integer a = map.get(key);
    System.out.println(key + " : " + a);
    
    /////////
    Set<String> set = map.keySet(); // 키에 대한 Set 객체
	System.out.println(set); //키값 쭈르륵 나옴

 

 

◾ map 값을 List 로 가져올 수 있음

List<Integer> list = new LinkedList<>(map.values());
System.out.println(list);

 

 

◾ map 값을 collection으로 가져올 수 있음

Collection<Integer> col = map.values(); //컬렉션 객체
		Iterator<Integer> it2 = col.iterator();
		while(it2.hasNext()) {{
			int n = it2.next();
			System.out.print(n + "  ");
		}

 

 

 

✔️ TreeMap

- 키, 값을 입력했을 때, 키로 정렬하는 map 이다.

- TreeMap<String, Integer>

//submap 쓰려고 treemap 씀! TreeMap<String, Integer>
		//키로 정렬. 키는 comparable 인터페이스가 구현 되어 있어야함.
	TreeMap<String, Integer> map = new TreeMap<>();
		map.put("자바", 95);
		map.put("오라클", 100);
		map.put("빅데이터", 90);
		map.put("서블릿", 90);
		map.put("스프링", 95);
		map.put("HTML", 100);
		
		System.out.println(map);
		
		
	//스피링에서 자바 이전까지 추출
	//submap : treemap 메소드
	Map<String, Integer> map2 = map.subMap("스프링", "자바"); 	//A, B : A에서 B 이전까지 출력
		System.out.println(map2);

 

 

 

 

 

블로그의 정보

개발자 미니민의 개발로그

mini_min

활동하기