Learn & Record
[코리아IT아카데미] Java - List, TreeSet, Map, Compare 본문
오름차순 : 작은 값 > 큰 값
내림차순 : 큰 값 > 작은 값
1. TreeSet
import java.util.Comparator;
import java.util.TreeSet;
class MyCompareInt implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2) * -1; // Integer 클래스의 compareTo() 메서드를 반대로
}
}
public class MyTreeSet02 {
public static void main(String[] args) {
TreeSet<Integer> score = new TreeSet<>(new MyCompareInt());
score.add(90);
score.add(100);
score.add(85);
score.add(65);
score.add(50);
score.add(75);
score.add(90);
System.out.println(score);
Integer value = null;
value = score.first(); // first(); 가장 작은 값 반환
print("가장 낮은 점수", value);
value = score.last(); // last() : 가장 큰 값
print("가장 높은 점수", value);
value = score.lower(85); // 제공된 값보다 작은 값 중 가장 큰 값 (인자값 미포함)
print("85 바로 이전 점수", value);
value = score.higher(85); // higher : 제공된 값도가 큰 값 중 가장 작은 값 (인자값 미포함)
print("85 바로 다음 점수", value);
value = score.floor(85);
print("85 또는 바로 이전 점수", value); // floor() : 제공된 값과 같거나 작은 값 중 가장 큰 값
value = score.ceiling(85); // ceiling() : 제공된 값돠 크거나 같은 값 중 가장 작은 값
print("85 또는 바로 다음 정수", value);
while (!score.isEmpty()) {
value = score.pollLast(); // pollLast() : 가장 큰 값은 반환 후 삭제
print("현재 가장 높은 점수", value);
}
}
public static void print(String s, Integer value) {
System.out.println(s + " : " + value);
}
}
2. compare 인터페이스 구현
- compare(a, b)
- 첫번째 파라미터 객체 < 두번째 파라미터 객체 : 음수 리턴
- 첫번째 파라미터 객체 == 두번째 파라미터 객체 : 0 리턴
- 첫번째 파라미터 객체 > 두번째 파라미터 객체 : 양수 리턴
- 음수 또는 0이면 객체의 자리가 그대로 유지, 양수이면 자리 변경
3. 평가
- 인터페이스 구현 및 추상 클래스 상속 리스트를 이용한 은행계좌
4. Map
- key-value를 하나의 쌍으로 묶어서 저장하는 자료구조 (다른 언어에서는 dictionary)
- key 중복불가, value 중복가능
메서드 | 설명 |
V put(K key, V value) | key에 해당하는 value 값을 map에 넣음 |
V get(K key) | key에 해당하는 value 값을 반환 |
5. Map 실습
import java.util.*;
public class MyMap01 {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("신용권", 85);
map.put("홍길동", 90);
map.put("동장군", 80);
map.put("홍길동", 95); // key가 같기 때문에 제일 마지막 저장한 값으로 대체
System.out.println("총 Entry 수 :" + map.size());
// 객체 찾기
// 이름(Key)으로 점수(Value)를 검색
System.out.println("\t홍길동: " + map.get("홍길동")); // key로 정수 값 검색
System.out.println();
// 객체를 하나씩 ㅓㅊ리
Set<String> keySet = map.keySet(); // keySet() : 모든 키를 Set 객체에 담아 리턴. key set 얻기
Iterator<String> keyIterator = keySet.iterator();
while (keyIterator.hasNext()) { // 반복해서 키를 얻고 값을 Map에서 얻어냄
String key = keyIterator.next();
Integer value = map.get(key);
System.out.println("\t" + key + " : " + value);
}
System.out.println();
// foreach문을 사용해 출력.
for(Map.Entry<String, Integer> entry : map.entrySet()) {
String strKey = entry.getKey();
Integer intValue = entry.getValue();
System.out.println(strKey + ":" + intValue);
}
System.out.println();
// foreach문을 사용해 출력.
for(var strKey : map.keySet()){
Integer intValue = map.get(strKey);
System.out.println(strKey + ":" + intValue);
}
System.out.println();
// 객체 삭제
map.remove("홍길동"); // 키로 map.Entry를 제거
System.out.println("총 Entry 수 : " + map.size());
// 객체를 하나씩 처리
// entrySet() : 키와 값의 쌍으로 구성된 모든 Map.Entry 객체를 Set에 담아서 리턴
Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
Iterator<Map.Entry<String, Integer>> entryIterator = entrySet.iterator();
while (entryIterator.hasNext()) {
Map.Entry<String, Integer> entry = entryIterator.next();
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("\t" + key + " : " + value);
}
System.out.println();
map.clear();
System.out.println("총 Entry 수 : " + map.size()); // 총 entry 수 : 0
}
}
6. Map 실습 2
import java.util.HashMap;
import java.util.Map;
class Student {
public int sno;
public String name;
public Student(int sno, String name) {
this.sno = sno;
this.name = name;
}
}
public class MyMap02 {
public static void main(String[] args) {
Map<Student, Integer> map = new HashMap<>();
map.put(new Student(1,"홍길동"), 95);
map.put(new Student(1,"홍길동"), 95);
map.put(new Student(1,"박유신"), 95);
System.out.println("총 Entry 수 : " + map.size()); //
}
}
7. List
- ArrayList
- 배열처럼 자료형의 집합이지만, 다르게 갯수의 제한이 없다.
import java.util.ArrayList;
public class Sample {
public static void main(String[] args) {
ArrayList pitches = new ArrayList();
pitches.add("138");
pitches.add("129");
pitches.add("142");
}
}
메서드 | 설명 |
add | 리스트에 값 추가 |
get | 리스트에 값 추출 |
size | 리스트 요소의 개수 출력 |
contains | 해당 항목 있는 지 판별 |
remove | 해당 값 삭제 |
'Dev > Java' 카테고리의 다른 글
JAVA JDBC (deposit, updateBalance, withdraw, selectOne, inquire, disConnect, accountDAO) (0) | 2024.02.19 |
---|---|
[코리아IT아카데미] JAVA - Exception (예외) (0) | 2024.02.02 |
[코리아IT아카데미] Java - Stack, Queue (스택, 큐), Set, HashSet (4) | 2024.01.26 |
[코리아IT아카데미] Java - Interface (2) | 2024.01.25 |