(2주차) JAVA 문법 종합반/2주차

16. 컬렉션 Stack, Queue, Set, Map

note994 2024. 8. 5. 11:34
//Stack : 수직으로 값을 쌓아놓고, 넣었다가 뺀다 FILO
// push, peek, pop
// 최근 저장된 데이터를 나열하고 싶거나, 데이터의 중복 처리를 막고 싶을 때 사용

Stack<Integer> intStack = new Stack<Integer>(); // 선언 및 생성

intStack.push(10);
intStack.push(15);
intStack.push(1);

while(!intStack.isEmpty()){ // intStack이 비어있지 않다면 반복
    System.out.println(intStack.pop()); // 가장 최근에 들어간 1이 출력되면서 1이 사라짐 -> 그 다음은 15, 10 순으로 intStack에서 빠져나온다.
}
//Stack : 수직으로 값을 쌓아놓고, 넣었다가 뺀다 FILO
// push, peek, pop
// 최근 저장된 데이터를 나열하고 싶거나, 데이터의 중복 처리를 막고 싶을 때 사용

Stack<Integer> intStack = new Stack<Integer>(); // 선언 및 생성

intStack.push(10);
intStack.push(15);
intStack.push(1);

System.out.println(intStack.peek()); // 최근 저장된 1이 출력됨. 1이 사라지진 않는다.
System.out.println(intStack.size()); 3

// Queue : FIFO
// add, peek, poll

Queue <Integer> intQueue = new LinkedList<>();

intQueue.add(1);
intQueue.add(5);
intQueue.add(9);

while(!intQueue.isEmpty()){
    System.out.println(intQueue.poll()); // 처음 들어간 값 1이 출력되고 1은 사라진다.
}
// Queue : FIFO
// add, peek, poll

Queue <Integer> intQueue = new LinkedList<>();

intQueue.add(1);
intQueue.add(5);
intQueue.add(9);


System.out.println(intQueue.peek()); // 처음 들어간 값 1을 초회한다.
System.out.println(intQueue.size());// intQueue의 크기 구하기

// Set(집합) : 순서 없고, 중복 없음
// 순서가 보장되지 않는 대신 중복을 허락하지 않도록 하는 프로그램에서 사용할 수 있는 자료구조
// Set-> 그냥 쓸 수도 있음, 그러나 HashSet,TreeSet 등으로 응용해서 같이 사용 가능

Set<Integer> intSet = new HashSet<>(); // 선언 및 생성

intSet.add(1);
intSet.add(12);
intSet.add(5);
intSet.add(9);
intSet.add(1);
intSet.add(12);

for(Integer value : intSet){
    System.out.println(value); // 중복값인 마지막의 1, 12 부분은 출력되지 않는다. 중복을 허용하지 않기 때문
}

//contains
System.out.println(intSet.contains(2)); // 2가 있니 없니? True 또는 False
System.out.println(intSet.contains(5)); // 5가 있니 없니? True 또는 False

// Map : Key - value pair -> 중요
// key라는 값으로 unique하게 보장이 돼야 함
// Map -> HashMap, TreeMap으로 응용

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

intMap.put("일",1);
intMap.put("이",2);
intMap.put("삼",3);
intMap.put("삼",4);
intMap.put("삼",5);

for(String key: intMap.keySet()){ // intMap의 key값만 가져오기
    System.out.println(key); //일이삼 3개만 출력됨, 중복 key값은 허용하지 않기 때문임
}

for(Integer key: intMap.valsues()){ // intMap의 value값만 가져오기
    System.out.println(key); //1,2,5가 출력됨, 중복된 key값은 없어지고 value 값은 덮어씌어진다.
}

System.out.println(intMap.get("삼")); // "삼" 이라는 key값의 value를 가져온다. -> 5