본문 바로가기

Java/java 기초

HashMap, TreeMap을 사용해서 추가및 검색, 삭제, 정렬 구현해보기

 

package main;

public class MyData {
	private int number;
	private String name;
	
	public MyData() {
		
	}
	
	public MyData(int number, String name) {
		super();
		this.number = number;
		this.name = name;
	}
	
	public int getNumber() {
		return number;
	}
	public void setNumber(int number) {
		this.number = number;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	

	@Override
	public String toString() {
		return "MyData [number=" + number + ", name=" + name + "]";
	}
}
package main;

import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeMap;

public class main1 {
	public static void main(String[] args) {
HashMap<Integer, MyData> dataMap = new HashMap<Integer, MyData>();
		
		MyData myData1 = new MyData(0, "온유");
		MyData myData2 = new MyData(3, "진형");
		MyData myData3 = new MyData(2, "규성");
		MyData myData4 = new MyData(1, "건욱");
		MyData myData5 = new MyData(4, "제균");
		
		dataMap.put(myData1.getNumber(), myData1);
		dataMap.put(myData2.getNumber(), myData2);
		dataMap.put(myData3.getNumber(), myData3);
		dataMap.put(myData4.getNumber(), myData4);
		dataMap.put(myData5.getNumber(), myData5);
		
		dataMap.remove(2);
		// 검색
		Iterator<Integer> iterator = dataMap.keySet().iterator();
		boolean b = dataMap.containsKey(1);
		System.out.println("b = " + b);
		// 수정
		MyData myData6 = new MyData(6, "제구");
		
		dataMap.replace(1, myData6);
		
		while(iterator.hasNext()) {
			int key = iterator.next();
			System.out.println("key : " + key);
			System.out.println("value : " + dataMap.get(key).toString());
		}

		
		// 정렬	
		TreeMap<Integer, MyData> tree = new TreeMap<Integer, MyData>(dataMap);
		
		//올림 차순
		Iterator<Integer> tkey = tree.keySet().iterator();
		
		while(tkey.hasNext()) {
			int key = tkey.next();
			
			System.out.println("key : " + key + " value : " + tree.get(key));
		}
		
	
	}
}

'Java > java 기초' 카테고리의 다른 글

HashMap , TreeMap 상속 을 활용하여 야구선수 관리 시스템 만들기  (0) 2019.12.02
LinkedList  (0) 2019.12.02
ArrayList  (0) 2019.11.29
Generic(제네릭)  (0) 2019.11.29
학생 성적 관리 프로그램 MVC 패턴으로 나누기  (0) 2019.11.29