ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 해시맵 사용시 유용한 메서드, 기능, 정렬
    컴퓨터 공부/JAVA 2020. 5. 23. 19:59

    코딩테스트 준비용으로 정리한 거...

     

    hashset -> 중복 허가 x, put한 순서 지켜지지 않음! (LinkedHashMap 사용!)

    키는 중복할 수 없고 value는 여러개 가능!! , null값도 가능 :)

    // HashMap 은 key 가 같고 값이 다르면 value를 덮어쓰기를 한다. 

    마지막으로 들어간 게 최종적으로 저장됨

    출처: https://link2me.tistory.com/1717 [소소한 일상 및 업무TIP 다루기]

     

    자바 해시맵 메서드 정리

    HashMap()

     

    - HashMap 객체를 생성

     

    ex) HashMap<String , Integer> map = new HashMap<String , Integer>();

     

          Map<String, Integer> map = new HashMap<String, integer>();

     

     

    void clear()

     

    - HashMap에 저장된 모든 객체를 제거한다. 

     

    ex) map.clear();

     

    Object clone()

     

    - 현재 HashMap을 복제하여 반환한다. 

     

    ex) newmap = (HashMap)map.clone();

     

    boolean containsKey(Object Key)

     

    - HashMap에 지정된 키(Key)가 포함되어 있는지 알려준다. 

     

    boolean containsValue(Object Value)

     

    - HashMap에 지정된 값(Value)가 포함되어 있는지 알려준다. 

     

    Set entrySet()

     

    - HashMap에 저장된 Key - Value갑슬 엔트리(키와 값을 결합)의 형태로 Set에 저장하여 반환

     

    ex) map.put("A", 1);

     

          map.put("B", 2);

     

          map.put("C", 3);

     

          Set set = map.entrySet();

     

          System.out.println("set values are" + set);

     

          (result) set values : [A=1,B=2,C=3]

     

    Object get(Object Key)

     

    - 지정된 Key 의 값을 반환한다. 

     

    ex) map.put("A", 1);

     

          map.put("B", 2);

     

          map.put("C", 3);

     

          String val = (String)map.get("B");

     

    System.out.println("Value for key B is: " + val);

     

     

     

    (result) Value for key B is 2

     

    bloolean isEmpty

     

    - HashMap이 비어있는지 확인한다.

     

    ex) boolean val = map.isEmpty();

     

    Set keySet()

     

    - HashMap에 저장된 모든 키가 저장된 Set을 반환한다.

     

    ex) map.put("A", 1);

     

          map.put("B", 2);

     

          map.put("C", 3);

     

          Set keyset = map.keySet();

     

          System.out.println("Key set values are" + keyset);

     

          (result) Key set values are [A,B,C]

     

    Object put(Object Key, Object Value)

     

    - HashMap에 키와 값을 저장.

     

    ex) map.put("A", "aaa");

     

          map.put("B", "bbb");

     

          map.put("C", "ccc");

     

    void putAll(Map m)

     

    - Map에 해당하는 모든 요소를 HashMap에 저장한다. 

     

    Object remove(Object Key)

     

    - HashMap에서 지정된 키로 지정된 값을 제거한다.

     

    ex) map.remove("key");

     

    int size()

     

    - HashMap에 저장된 요소의 개수를 반환한다. 

     

    Collection values()

     

    - HashMap에 저장된 모든 값을 컬렉션 형태로 반환한다. 



    출처: https://vaert.tistory.com/107 [Vaert Street]



    keyset->Object / String

    String[] mKeys = map.keySet().toArray(new String[map.size()]);

    Object[] mapkey = testMap.keySet().toArray();

    Arrays.sort(mapkey);

    출처: https://link2me.tistory.com/1717 [소소한 일상 및 업무TIP 다루기]


    key/ value 값으로 정렬

     

    key로 정렬

    Object[] mapkey = testMap.keySet().toArray();

    Arrays.sort(mapkey);

     

     

    더보기

    int compare 메서드를 간단히 설명하자면, 정렬이 진행될 때 자리바꿈(=정렬) 여부를 결정하는 값을 넘겨주는 역할을 한다.
    만약 return값이 0이나 음수이면 자리바꿈을 하지 않고, 양수이면 자리바꿈을 수행한다.
    만약 오름차순이 아니라 내림차순으로 정렬하고 싶다면 매개변수의 순서를 바꿔주면 된다.

    https://m.blog.naver.com/occidere/220918234464

     

    [정렬] Comparable과 Comparator

    자바에서 정렬을 하다 보면 Comparable과 Comparator를 자주 마주치게 된다. 본 게시글에서는 Comparabl...

    blog.naver.com

    value로 오름차순

    Map<String, Integer> testMap = new HashMap<String, Integer>();
    
    		// Map에 데이터 추가
    		testMap.put( "apple", 1);
    		testMap.put( "orange", 2);
    		testMap.put( "pineapple", 4);
    		testMap.put( "strawberry", 5);
    		testMap.put( "melon", 3);
    
    		// Map.Entry 리스트 작성
    		List<Entry<String, Integer>> list_entries = new ArrayList<Entry<String, Integer>>(testMap.entrySet());
    
    		// 비교함수 Comparator를 사용하여 오름차순으로 정렬
    		Collections.sort(list_entries, new Comparator<Entry<String, Integer>>() {
    			// compare로 값을 비교
    			public int compare(Entry<String, Integer> obj1, Entry<String, Integer> obj2) {
    				// 오름 차순 정렬
    				return obj1.getValue().compareTo(obj2.getValue());
    			}
    		});
    
    		System.out.println("오름 차순 정렬");
    		// 결과 출력
    		for(Entry<String, Integer> entry : list_entries) {
    			System.out.println(entry.getKey() + " : " + entry.getValue());
    		}

    내림차순

    Map<String, Integer> testMap = new HashMap<String, Integer>();
    
    		// Map에 데이터 추가
    		testMap.put( "apple", 1);
    		testMap.put( "orange", 2);
    		testMap.put( "pineapple", 4);
    		testMap.put( "strawberry", 5);
    		testMap.put( "melon", 3);
    
    		// Map.Entry 리스트 작성
    		List<Entry<String, Integer>> list_entries = new ArrayList<Entry<String, Integer>>(testMap.entrySet());
    
    		// 비교함수 Comparator를 사용하여 내림 차순으로 정렬
    		Collections.sort(list_entries, new Comparator<Entry<String, Integer>>() {
    			// compare로 값을 비교
    			public int compare(Entry<String, Integer> obj1, Entry<String, Integer> obj2)
    			{
    				// 내림 차순으로 정렬
    				return obj2.getValue().compareTo(obj1.getValue());
    			}
    		});
    
    		System.out.println("내림 차순 정렬");
    		// 결과 출력
    		for(Entry<String, Integer> entry : list_entries) {
    			System.out.println(entry.getKey() + " : " + entry.getValue());
    		}

    TreeMap은 put 메서드를 사용해 값을 저장하면 자동으로 정렬 (key로)

    import java.util.Map;
    import java.util.TreeMap;
    
    public class Main {
    
    	public static void main(String[] args) {
    		// Map 선언
    		Map<Integer, String> testMap = new TreeMap<Integer, String>();
    
    		// Map에 데이터 저장
    		testMap.put(1, "apple");
    		testMap.put(5, "pineapple");
    		testMap.put(2, "orange");
    		testMap.put(3, "strawberry");
    		testMap.put(4, "melon");
    
    		// 결과 출력
    		for (Integer nKey : testMap.keySet())
    		{
    			System.out.println(testMap.get(nKey));
    		}
    	}
    
    }

     

    https://ponyozzang.tistory.com/404

     

    JAVA Map 키(Key) 값(Value) 정렬 방법과 자동 정렬 예제

    자바에서 HashMap에 저장한 데이터를 키(Key) 또는 값(Value)으로 정렬하는 방법을 알아보겠습니다. HashMap 키(Key) 정렬 먼저 HashMap을 키(Key)로 정렬하는 방법을 보겠습니다. HashMap을 정렬하기 위해서는

    ponyozzang.tistory.com


    만약 입력된 Key의 순서가 보장되어야 한다면 LinkedHashMap을 사용하면 된다.

    LinkedHashMap은 put을 통해 입력된 순서대로 Key가 보장되므로 해당 문제를 해결할 수 있다. 물론 사용법은 HashMap과 동일하다.

    출처: https://fruitdev.tistory.com/141 [과일가게 개발자]

Designed by Tistory.