JAV)0517-1 컬렉션 프레임워크 3 : map

조한미르·2024년 5월 17일
0
import java.util.Hashmap;
improt.util.Map;

public class MapExam {
	public static void main(String[] args) {
    
    Map<String, Integer> map = new Hashmap<>();
    
    //입력
    map.put("one",1);
    map.put("two",2);
    map.put("two",22); // 맵에서의 키중복은 값을 치환 떄문에 get(two);시 22 
    map.put("three",3);
    map.put("four",4);
    map.put("five",5);
    
    
    System.out.println("map의 사이즈 : " + map.size());
    -> map 의 사이즈 : 5
    
    map.remove("five");
   	System.out.println("map의 사이즈 : " + map.size());
    -> map 의 사이즈 : 4
    
    System.out.println("map has that key name is one : " + map.containsKey("one"));
    -> map has that key name is one : true
	System.out.println("map has that key name is six : " + map.containsKey("six"));
    -> map has that key name is six : false
    
    System.out.println("map has that value 1 : " + map.containsKey("one"));
    -> map has that value 1 : true
    System.out.println("map has that value 2 : " + map.containsKey("2"))
    -> map has that value 2 : false
    
    
    //출력형태
    
    /// key를 이용한 출력
    
    Set<String>keySet = map.keySet();
    
    for(String key : keySet) {
    	System.out.println(map.get(key));
        
        -> 4
           1 
           22
           3    
    }
  }
}

-> map 의 사이즈 : 5
  • List, Set, Map 사용시기
    - Lis
    - 단순 삽입, 삭제
    • Set
      • 중복제거
    • Map
      • 검색해서 분류할 때

Map 예제)

improt java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class MapExam02 {
	
    public static void main(String[] args){
    
    String[] flowers = {"백합", "장미", "안개꽃", "튤립", "장미", "장미", "백힙", "튤립", "안개꽃"};
    
    //꽃별로 몇개씩 있는지 파악
    Map<String, Integer> flMap = new HashMap<>();
    int cout = 0;
    for(int i = 0; i < flowers.length; i++) {
    	//꽃이름 가져오기
    	String flowers = flowers[i];
        
        //꽃이름과 동일한 key를 가지고 있다면
        if(flMap.containsKey(flower)){
        	// 한개 갯수에 한개를 더한다
        	count = flMap.et(flower) + 1;
            //맵에 치환 - key중복 치환 이용
            flMap.put(flower, count);
        }else{
        	//중복이 없다면 맵에 등록
        	flMap.put(flower, 1);
        }
    }
    
    //출력을 위해 KeySet가져오기
    Set<String> keySet = flMap.keySet();
    
    for(String key : keySet){
    	System.out.println("꽃 : " + key + " 갯수 : " + flMap.get"(key));
    }
  }
}


->: 튤립, 갯수 : 2: 안개꽃, 갯수 : 2: 장미, 갯수 : 3: 백합, 갯수 : 2
profile
꼭 해내는 사람

0개의 댓글