일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
- oracle
- joinpoint
- LexicalScope
- ProjectFacets
- jdk
- SQL
- URIMalformedURIException
- curryr
- URIMalformedURI오류
- 자유변수
- javaversion
- Spring
- ArrayLike
- Eclipse
- tomcat
- ModulesPath
- 일급객체
- TargetObject
- URIMalformedURI
- map
- AfterReturnning
- URI$MalformedURIException
- springversion
- javacversion
- AOP
- SpringFramework
- REGEXP_COUNT
- xml
- Annotation
- NewServer
- Today
- Total
잼's Tech
[JAVA] 컬렉션(Collection) 프레임워크 본문
[JAVA] 컬렉션(Collection) 프레임워크
컬렉션?
여러 자료를 효율적으로 보관 및 처리하기 위한 자료구조
배열의 단점을 보완
- 사이즈가 동적
- 어떤 자료형이라도 상관 없음
컬렉션 프레임워크?
여러 자료를 효율적으로 관리하기 위한 라이브러리
컬렉션(Collection) 프레임워크
LIST | - 순서가 있음 - 중복 허용 |
Linked List | ● 양방향 포인터 ● 삽입, 삭제 유용 ● 스택, 큐 등 만듬 |
Vector | ● 대용량 처리 ● 내부 자동 동기화 ● 잘 안쓰임... |
||
Array List | ● 단방향 포인터 ● 인덱스 있어 조회 유용 |
||
SET | - 순서가 없음 - 중복 허용 안함 |
Hash Set | ● 가장 빠른 임의 접근 |
Tree Set | ● 정렬 방법 지정 가능 | ||
MAP | - 키와 값의 쌍 | Hash Map | ● null 값 가능 |
Hash Table | ● Hash Map보다 느리나 동기화 지원 | ||
Tree Map | ● 정렬이 되어 있어 검색이 빠름 |
▶ L I S T
선언 및 생성
List<타입> li1 = new LinkedList();
List<타입> li2 = new Vector();
List<타입> li3 = new ArrayList();
함수
추 가 | add() | ● 요소 추가 | li1.add("a") → 요소 a 추가 |
addAll() | ● 컬렉션을 받아 모두 추가 | li1.add(li2) → li1에 li2의 요소들 추가 |
삭 제 | remove() | ● 요소 삭제 인덱스 번호를 줄 수도 있고 값을 줄 수도 있다 |
li1.remove("a") → a라는 요소 삭제 li1.remove(0) → 0번 인덱스의 값 삭제 |
removeAll() | ● 컬렉션 받아 컬렉션의 인자들이 list에 있으면 삭제 | li1 = [1,2,3] li2 = [2,3,4] li1.removeAll(li2) → li1 = [1] |
|
retainAll() | ● 컬렉션 받아 필터 역할로 삭제 | li1 = [1,2,3] li2 = [2,3,4] li1.retainAll(li2) → li1 = [2,3] |
G E T | get() | ● 요소 가져오기 | li1.get(0) → 0번 인덱스의 값 가져옴 |
S E T | set() | ● 요소 세팅하기 | li1.set(0, "pp") → 0번 인덱스의 값 pp로 설정 |
비 교 | contains() | ● 객체 있는지 확인 | li1.contains("a") → a 요소 있으면 return true |
containsAll() | ● 2개의 list의 값들이 같은지 비교 | li1 = [1,2,3] li2 = [2,3,1] li1.containtsAll(li2) → true |
|
equals() | ● 2개의 list의 값들이 같은지 비교 - containsAll()과의 차이는 순서도 봄 |
li1 = [1,2,3] li2 = [2,3,1] li1.containtsAll(li2) → false |
교 체 | replaceAll() | ● 모든 요소 교체 | li1.replaceAll(a -> a.toUpperCase()) → 모두 대문자로 |
분 할 | subList() | ● List 자르기 | li1.subList(0, 2) → 0번에서 ~ 1번까지 잘라옴 |
Iterator | iterator() | ● iterator 반환 | li1.iterator() |
listIterator() | ● listIterator 반환 listIterator : iterator + 추가 기능 |
li1.listIterator() |
기 타 | sort() | ● 정렬 | 향 후 더 깊게 들어갈 예정 |
clear() | ● 값들 null로 초기화, size = 0 | li1.clear() → 초기화 | |
indexOf() | ● 요소의 인덱스 번호 반환(없으면 -1) 여러 개일 경우 맨 처음 나타난 인덱스 번호 반환 |
li1.indexOf("a") → 가장 처음 a 인덱스 | |
lastIndexOf() | ● 여러 개일 경우 맨 마지막 나타난 인덱스 번호 반환 |
li1.lastindexOf("a") → 가장 마지막 a 인덱스 | |
size() | ● List의 크기 return | li1.size() → return 크기 | |
isEmpty() | ● 비어있는지 확인 | li1.isEmpty() → 비었으면 true | |
toArray() | ● List의 값들을 배열(Array)로 만들어 반환 | String[] str = li1.toArray(new String[0]) → 0이라 동적으로 li1크기만큼 형성 |
▶ S E T
선언 및 생성
Set<타입> se1 = new HashSet<>();
Set<타입> se2 = new TreeSet<>();
함수
List의 함수들과 거의 대부분 비슷하나 몇몇 함수가 빠졌다고 생각하면 된다.
List에서 함수를 정리하여 놓았으니 이번에는 사용이 가능한 함수들을 예제로 보여주는 식으로 설명을 이어갈 것이다.
● Add()
se1.add("jaem");
System.out.println(se1);
출력: [jaem]
● AddAll()
se1.add("A");
se1.add("B");
se2.add("C");
se2.add("D");
se1.addAll(se2);
System.out.println(se1);
출력: [A, B, C, D]
● Remove()
se1.add("A");
se1.remove("A");
System.out.println(se1);
출력: []
● RemoveAll()
se1.add("A");
se1.add("B");
se1.add("C");
se2.add("B");
se2.add("C");
se2.add("D");
se1.removeAll(se2);
System.out.println(se1);
출력: [A]
● Contains()
se1.add("A");
System.out.println(se1.contains("A"));
출력: true
● ContainsAll()
se1.add("A");
se1.add("B");
se2.add("B");
se2.add("A");
System.out.println(se1.containsAll(se2));
출력: true
● Equals()
se1.add("A");
se1.add("B");
se2.add("B");
se2.add("A");
System.out.println(se1.equals(se2));
출력: true
※ SET은 순서가 없기에 true다
● Iterator()
System.out.println(se1.iterator().toString());
출력: java.util.HashMap$KeyIterator@~~~
● Size()
se1.add("A");
System.out.println(se1.size());
출력: 1
● Clear()
se1.add("A");
se1.clear();
System.out.println(se1.size());
출력: 0
● IsEmpty()
se1.add("A");
System.out.println(se1.isEmpty());
출력: false
● ToArray()
se1.add("DOG");
se1.add("CAT");
se1.add("HORSE");
String[] str = se1.toArray(new String[0]);
for(String st : str) {
System.out.print(st + " ");
}
출력: HORSE CAT DOG
※ SET이기에 랜덤 순서로 빠져나와 만들어진다.
▶ M A P
: Value는 중복 가능, Key는 중복 불가능
선언 및 생성
Map<타입, 타입> mp1 = new HashMap();
Map<타입, 타입> mp2 = new TreeMap();
Map<타입, 타입> mp3 = new Hashtable();
함수
▷ 추가
● put()
: Key, Value 쌍 추가
mp1.put(1, "A");
System.out.println(mp1);
출력: {1=A}
● putAll()
: Map과 Map 합치기
mp1.put(1, "A");
mp1.put(2, "B");
mp2.put(2, "C");
mp2.put(3, "D");
mp1.putAll(mp2);
System.out.println(mp1);
출력: {1=A, 2=C, 3=D}
※ Key가 같을 경우, mp2의 Value로 mp1의 Value를 덮는다.
● merge()
: 2개의 Map 합치기
mp1.put(1, "A");
mp1.put(2, "B");
mp2.put(2, "C");
mp2.put(3, "D");
mp2.forEach((K,V) -> mp1.merge(K, V, (V1,V2) -> V2));
System.out.println(mp1);
출력: {1=A, 2=C, 3=D}
※ mp1에 mp2를 합치기
● putIfAbsent()
: 해당 Key 값이 없을 때 Key, Value 쌍 추가
mp1.put(1, "A");
mp1.putIfAbsent(1, "B");
mp1.putIfAbsent(2, "C");
System.out.println(mp1);
출력: {1=A, 2=C}
● computeIfAbsent()
: 해당 Key 값이 없을 때 Value에 함수 수행하여 추가
mp1.put(1, "A");
mp1.computeIfAbsent(1, (K)->K.toString()+"ㅎㅎ");
mp1.computeIfAbsent(2, (K)->K.toString()+"ㅎㅎ");
System.out.println(mp1);
출력: {1=A, 2=2ㅎㅎ}
※ putIfAbsent과 다르게 2번째 인자에 수행할 함수를 넣는다.
● computeIfPresent()
: 해당 Key 값이 있을 때 요소 추가(덮어씀)
mp1.put(1, "A");
mp1.computeIfPresent(1, (K,V)-> V+"ㅎㅎ");
mp1.computeIfPresent(2, (K,V)-> V+"ㅎㅎ");
System.out.println(mp1);
출력: {1=Aㅎㅎ}
● compute()
: Key 값이 있을 때도 함수 실행
mp1.put(1, "A");
mp1.compute(1, (K,V)-> V+"ㅎㅎ");
mp1.compute(2, (K,V)-> V+"ㅎㅎ");
System.out.println(mp1);
출력: {1=Aㅎㅎ, 2=nullㅎㅎ}
▷ 가져오기
● get()
: Key에 해당하는 Value 반환
mp1.put(1, "A");
mp1.put(2, "B");
System.out.println(mp1.get(1));
출력: 1
● getOrDefault()
: Key 있을 시 Value 반환, 없을 시 return 값 주기
mp1.put(1, "A");
System.out.println(mp1.get(1));
System.out.println(mp1.getOrDefault(2,"ㅎㅎ"));
System.out.println(mp1);
출력: A
ㅎㅎ
{1=A}
▷ 삭제
● remove()
: 주어진 Key에 해당하는 Key, Value 쌍 삭제
mp1.put(1, "A");
mp1.put(2, "B");
mp1.remove(1);
System.out.println(mp1);
출력: {2=B}
▷ 교체
● replace()
: 주어진 Key 값에 해당하는 Value 교체
mp1.put(1, "A");
mp1.put(2, "B");
mp1.replace(1,"G");
System.out.println(mp1);
출력: {1=G, 2=B}
● replaceAll()
: 모든 Key, Value 쌍에 주어진 함수 실행하여 교체
mp1.put(1, "A");
mp1.put(2, "B");
mp1.replaceAll((K,V)->V+"ㅎㅎ");
System.out.println(mp1);
출력: {1=Aㅎㅎ, 2=Bㅎㅎ}
▷ 비교
● containsKey()
: Key가 있는지 비교하여 True or False 반환
mp1.put(1, "A");
mp1.put(2, "B");
System.out.print(mp1.containsKey(1)+" ");
System.out.println(mp1.containsKey(3));
출력: true false
● containsValue()
: Value가 있는지 비교하여 True or False 반환
mp1.put(1, "A");
mp1.put(2, "B");
System.out.print(mp1.containsValue("A")+" ");
System.out.println(mp1.containsValue("C"));
출력: true false
● equals()
: Key, Value 쌍들을 비교하여 Map과 Map 비교
mp1.put(1, "A");
mp1.put(2, "B");
mp2.put(1, "A");
mp2.put(2, "B");
System.out.println(mp1.equals(mp2));
출력: true
▷ Return Collection
● entrySet()
: 키와 값 모두 SET 계열로 리턴
mp1.put(1, "A");
mp1.put(2, "B");
System.out.print(mp1.entrySet() instanceof Set);
System.out.println(" / " + mp1.entrySet());
출력: true / [1=A, 2=B]
※ Set 계열로 만들어 return 해줬기에 Set 계열의 함수 사용이 가능하다.
● keySet()
: 키만 모아 SET 계열로 리턴
mp1.put(1, "A");
mp1.put(2, "B");
System.out.print(mp1.keySet() instanceof Set);
System.out.println(" / " + mp1.keySet());
출력: true / [1, 2]
※ entrySet과 다르게 Key만 모아서 Set 계열로 만들어 return 해준다.
● values()
: value들만 모아 Collection 계열로 리턴
mp1.put(1, "A");
mp1.put(2, "B");
System.out.print(mp1.values() instanceof Collection);
System.out.println(" / " + mp1.values());
출력: true / [A, B]
※ keySet과 다르게 Value만 모아서 Collection 계열로 만들어 return 해준다.
▷ 기타
● forEach()
: 전체 순회
mp1.put(1, "A");
mp1.put(2, "B");
mp1.forEach((K,V) -> System.out.print(K + "-" + V + " "));
출력: 1-A 2-B
※ 모든 Key, Value를 돌며 주어진 특정 작업을 한다.
● size()
: Map의 Key, Value 쌍의 개수를 return (크기)
mp1.put(1, "A");
mp1.put(2, "B");
System.out.println(mp1.size());
출력: 2
● clear()
: 모든 Key, Value 쌍을 지우고 크기를 0으로 만든다. (초기화)
mp1.put(1, "A");
mp1.put(2, "B");
mp1.clear();
System.out.println(mp1.size());
출력: 0
● isEmpty()
: 비었는지
mp1.put(1, "A");
mp1.put(2, "B");
System.out.print(mp1.isEmpty() + " ");
mp1.clear();
System.out.print(mp1.isEmpty());
출력: false true
※ Map에는 Iterator가 없기에 Collection 계열로 만든 후 iterator() 함수를 불러와야한다.
mp1.put(1, "A");
mp1.put(2, "B");
System.out.print(mp1.keySet().iterator() instanceof Iterator);
출력: true
※EntrySet의 경우
Map<Integer,String> mp1 = new HashMap();
mp1.put(1, "A");
mp1.put(2, "B");
Iterator<Map.Entry<Integer, String>> it = mp1.entrySet().iterator();
※ ITERATOR
Iterator는 JAVA Collection Framework에서 요소들을 읽어오는 방법을 표준화한 것
→ 결국, 좀 더 쉽게 데이터를 읽기 위한 인터페이스라고 생각하면 된다.
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
Iterator it = list.iterator();
가 있다고 하자.
● hasNext() : 자신의 위치 다음에 데이터가 있는지 확인
● next() : 자신의 위치를 다음으로 이동 후 데이터 return
● remove() : 자신의 위치에 있는 데이터를 삭제 후 뒤의 데이터들을 한칸 씩 앞으로 당겨옴
'기타 개념 정리' 카테고리의 다른 글
Meta Character (0) | 2021.08.09 |
---|---|
렉시컬 스코프 (0) | 2021.08.09 |