HashMap 예제 코드

Jane·2023년 2월 22일
0

IT 수업 정리

목록 보기
50/124

HashMap Summary

  • HashMap<>을 이용하여 Key와 Value를 받는다.
  • Set<> (객체명) = [맵 객체].keySet()으로 Map 객체의 Key와 Value를 얻어올 수 있다.
    • key는 맵 객체 안에 있는 인덱스 순으로 있다
    • value는 [맵 객체].get(인덱스)로 구할 수 있다
    • containsKey()로 Map 안에 key가 있는지 비교한다.
  • equals는 문자를 비교할 때 쓴다.
    • Object에서 가져와서 equals로 비교할 때 instanceof 연산자를 통하여 객체가 포함되어 있는지 확인하고 비교하는 것을 추천한다
  • 입력을 실행하려고 할 때는 try ~ catch로 Exception을 잡는다
  • 알고리즘을 풀이한 후, 객체지향 코드로 바꿔보도록 한다

1. 나라 이름과 인구 수를 관리하는 HashMap 프로그램

1-1. 문제와 입력 예시

나라 이름과 인구를 입력하세요. (예: Korea 5000)
나라 이름, 인구 >> Korea 5000
나라 이름, 인구 >> USA 1,000,000
나라 이름, 인구 >> Swiss 2000
나라 이름, 인구 >> France 3000
나라 이름, 인구 >> 그만


인구 검색 >> France
France의 인구는 3000
인구 검색 >> 스위스
스위스 나라는 없습니다.
인구 검색 >> 그만

1-2. 알고리즘 코드

import java.util.*;

class JavaPractice {

	public static void main(String[] args) {
		Map<String, Integer> cMap = new HashMap<>();
		Scanner sc = new Scanner(System.in);

		try {
			while (true) {
				System.out.print("나라 이름과 인구 수를 입력 >>");
				String country = sc.next();
				if (country.equals("그만")) {
					// 종료
					System.out.println("입력을 종료합니다");
					break;
				}
				int pp = sc.nextInt();
				cMap.put(country, pp);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			while (true) {
				System.out.print("인구 검색 >>");
				String search = sc.next();

				if (search.equals("그만")) {
					System.out.println("검색을 종료합니다");
					break;
				} else if (cMap.containsKey(search)) {// cMap에 search가 있는지 확인
					System.out.println(search + "의 인구 수는 " + cMap.get(search));
				} else {
					System.out.println(search + "는 리스트에 없습니다.");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

[Console]
나라 이름과 인구 수를 입력 >>Korea 5000
나라 이름과 인구 수를 입력 >>USA 1000000
나라 이름과 인구 수를 입력 >>Swiss 2000
나라 이름과 인구 수를 입력 >>France 3000
나라 이름과 인구 수를 입력 >>그만
입력을 종료합니다
인구 검색 >>France
France의 인구 수는 3000
인구 검색 >>Japan
Japan는 리스트에 없습니다.
인구 검색 >>그만
검색을 종료합니다

1-3. 객체지향 코드

import java.util.*;

class CountryMap {
	Map<String, Integer> cMap;
	Scanner sc;

	public CountryMap() {
		cMap = new HashMap<>();
		sc = new Scanner(System.in);
	}

	public void countryPut() {
		try {
			while (true) {
				System.out.print("나라 이름과 인구 수를 입력 >>");
				String country = sc.next();
				if (country.equals("그만")) {
					// 종료
					System.out.println("입력을 종료합니다");
					break;
				}
				int pp = sc.nextInt();
				cMap.put(country, pp);
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(0);
		}
	}

	public void countrySearch() {
		try {
			while (true) {
				System.out.print("인구 검색 >>");
				String search = sc.next();

				if (search.equals("그만")) {
					System.out.println("검색을 종료합니다");
					break;
				} else if (cMap.containsKey(search)) {// cMap에 search가 있는지 확인
					System.out.println(search + "의 인구 수는 " + cMap.get(search));
				} else {
					System.out.println(search + "는 리스트에 없습니다.");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(0);
		}
	}

}

class JavaPractice {

	public static void main(String[] args) {
		CountryMap country = new CountryMap();
		country.countryPut();
		country.countrySearch();

	}

}

2. 도시의 경도와 위도를 관리하는 HashMap 프로그램

2-1. 문제와 입력 예시

도시 이름, 위도, 경도 정보를 가진 Location 클래스를 작성하고,
도시 이름을 '키'로 하는 HashMap<String, Location> 컬렉션을 만들고,
사용자로부터 입력 받아 4개의 도시를 저장하라.
그리고 도시 이름으로 검색하는 프로그램을 작성하라.

도시, 경도, 위도를 입력하세요.

(입력)
⨠ 서울, 37, 126
⨠ LA, 34, -118
⨠ 파리, 2, 48
⨠ 시드니, 151, -33

(리스트 출력)
서울 : 37, 126
LA : 34, -118
파리 : 2, 48
시드니 : 151, -33

(검색)
도시 이름 >> 피리
피리는 없습니다.
도시 이름 >> 파리
파리 2 48
도시 이름 >> 그만

2-2. 알고리즘 코드

import java.util.*;

class Location {
	private String city; // 도시 이름
	private int longitude; // 경도
	private int latitude; // 위도

	public Location(String city, int longitude, int latitude) {
		this.city = city;
		this.longitude = longitude;
		this.latitude = latitude;
	}

	public String getCityname() {
		return city;
	}

	public int getLongitude() {
		return longitude;
	}

	public int getLatitude() {
		return latitude;
	}

	@Override
	public String toString() {
		return (city + ": 경도 " + longitude + " 위도 " + latitude);
	}

}

public class JavaTest {
	public static void main(String[] args) {
		Map<String, Location> map = new HashMap<>();
		Scanner scan = new Scanner(System.in);

		// 입력하고 해쉬맵 만들기
		System.out.println("도시, 경도, 위도를 입력하세요 >> ");
		while (map.size() < 4) {
			try {
				System.out.print("도시 : ");
				String city = scan.next();
				int num1 = scan.nextInt();
				int num2 = scan.nextInt();

				Location location = new Location(city, num1, num2);
				map.put(city, location);
			} catch (Exception e) {
				e.printStackTrace();
				System.exit(0);
			}
		}

		// 출력하기
		System.out.println("==============");

		Set<String> key = map.keySet();
		for (Iterator<String> itr = key.iterator(); itr.hasNext();) {
			System.out.println(map.get(itr.next()));
		}
		System.out.println("==============");

		// 검색하기
		try {
			while (true) {
				System.out.print("도시 검색 >> ");
				String search = scan.next();

				if (search.equals("그만")) {
					System.out.println("검색을 종료합니다");
					break;
				} else if (map.containsKey(search)) {
					System.out.println(map.get(search));
				} else {
					System.out.println(search + "는 리스트에 없습니다.");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(0);
		}

	}
}

[Console]
도시, 경도, 위도를 입력하세요 >>
도시 : 서울 37 126
도시 : LA 34 -118
도시 : 파리 2 48
도시 : 시드니 151 -33


서울: 경도 37 위도 126
LA: 경도 34 위도 -118
파리: 경도 2 위도 48
시드니: 경도 151 위도 -33


도시 검색 >> 시드니
시드니: 경도 151 위도 -33
도시 검색 >> 사드니
사드니는 리스트에 없습니다.
도시 검색 >> 그만
검색을 종료합니다

2-3. 객체지향 코드

import java.util.*;

class Location {
	private String city; // 도시 이름
	private int longitude; // 경도
	private int latitude; // 위도

	public Location(String city, int longitude, int latitude) {
		this.city = city;
		this.longitude = longitude;
		this.latitude = latitude;
	}

	public String getCityname() {
		return city;
	}

	public int getLongitude() {
		return longitude;
	}

	public int getLatitude() {
		return latitude;
	}

	@Override
	public String toString() {
		return (city + ": 경도 " + longitude + " 위도 " + latitude);
	}

}

class LocationMapping {
	Map<String, Location> map;
	Scanner scan;

	public LocationMapping() { // 생성자 함수
		map = new HashMap<>();
		scan = new Scanner(System.in);
	}

	public void locationInput() { // 입력하고 해쉬맵 만들기
		System.out.println("도시, 경도, 위도를 입력하세요 >> ");
		while (map.size() < 4) {
			try {
				System.out.print("도시 : ");
				String city = scan.next();
				int num1 = scan.nextInt();
				int num2 = scan.nextInt();

				Location location = new Location(city, num1, num2);
				map.put(city, location);
			} catch (Exception e) {
				e.printStackTrace();
				System.exit(0);
			}
		}

	}

	public void locationShow() { // 출력하기
		Set<String> key = map.keySet();
		for (Iterator<String> itr = key.iterator(); itr.hasNext();) {
			System.out.println(map.get(itr.next()));
		}
	}

	public void locationSearch() { // 검색하기
		try {
			while (true) {
				System.out.print("도시 검색 >> ");
				String search = scan.next();

				if (search.equals("그만")) {
					System.out.println("검색을 종료합니다");
					break;
				} else if (map.containsKey(search)) {
					System.out.println(map.get(search));
				} else {
					System.out.println(search + "는 리스트에 없습니다.");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(0);
		}
	}

}

public class JavaTest {
	public static void main(String[] args) {

		LocationMapping lm = new LocationMapping();
		lm.locationInput();
		System.out.println("==============");
		lm.locationShow();
		System.out.println("==============");
		lm.locationSearch();
	}
}
profile
velog, GitHub, Notion 등에 작업물을 정리하고 있습니다.

0개의 댓글