Collections (Stack, Queue, Tree Set, Tree Map, Properties)

dykwon·2024년 1월 17일

Stack

import java.util.Stack;

public class StackExample {

    public static void main(String[] args) {
        Stack<String> stack = new Stack<>();

        // Pushing elements onto the stack
        stack.push("Element1");
        stack.push("Element2");
        stack.push("Element3");

        // Popping elements from the stack
        while (!stack.isEmpty()) {
            System.out.println("Popped: " + stack.pop());
        }
    }
}

Queue

Java LinkedList 는 List와 Queue를 구현한 LinkedList가 있다.

import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {

    public static void main(String[] args) {
        Queue<String> queue = new LinkedList<>();

        // Enqueuing elements into the queue
        queue.offer("Element1");
        queue.offer("Element2");
        queue.offer("Element3");

        // Dequeuing elements from the queue
        while (!queue.isEmpty()) {
            System.out.println("Dequeued: " + queue.poll());
        }
    }
}

TreeSet

이진트리의 특성을 갖는 Set 으로 이진트리의 특성에 따라 자동 정렬된다.

  1. add(E e):

    • TreeSet에 요소를 추가합니다.
  2. remove(Object o):

    • 주어진 요소를 TreeSet에서 제거합니다.
  3. contains(Object o):

    • 주어진 요소가 TreeSet에 포함되어 있는지 여부를 확인합니다.
  4. first():

    • TreeSet의 첫 번째 요소를 반환합니다.
  5. last():

    • TreeSet의 마지막 요소를 반환합니다.
  6. subSet(E fromElement, E toElement):

    • 주어진 범위에 속하는 부분집합을 반환합니다.
import java.util.TreeSet;

public class TreeSetExample {

    public static void main(String[] args) {
        TreeSet<Integer> treeSet = new TreeSet<>();

        // Adding elements to the TreeSet
        treeSet.add(3);
        treeSet.add(1);
        treeSet.add(2);

        // Iterating over the elements in sorted order
        for (int element : treeSet) {
            System.out.println("Element: " + element);
        }
        
        treeSet.fisrt();
        treeSet.last();
        treeSet.lower(new Integer(2));
        
    }
}

TreeMap 내장 함수:

이진트리의 특성을 갖는 Map 으로 이진트리의 특성에 따라 자동 정렬된다.

  1. put(K key, V value):

    • TreeMap에 키와 값의 쌍을 추가합니다.
  2. remove(Object key):

    • 주어진 키에 해당하는 항목을 TreeMap에서 제거합니다.
  3. get(Object key):

    • 주어진 키에 해당하는 값을 반환합니다.
  4. containsKey(Object key):

    • 주어진 키가 TreeMap에 존재하는지 여부를 확인합니다.
  5. firstKey():

    • TreeMap의 첫 번째 키를 반환합니다.
  6. lastKey():

    • TreeMap의 마지막 키를 반환합니다.
  7. subMap(K fromKey, K toKey):

    • 주어진 범위에 속하는 부분맵을 반환합니다.
import java.util.TreeMap;

public class TreeMapExample {

    public static void main(String[] args) {
        TreeMap<String, Integer> treeMap = new TreeMap<>();

        // Putting key-value pairs into the TreeMap
        treeMap.put("Three", 3);
        treeMap.put("One", 1);
        treeMap.put("Two", 2);

        // Iterating over the entries in sorted order of keys
        for (String key : treeMap.keySet()) {
            System.out.println("Key: " + key + ", Value: " + treeMap.get(key));
        }
        
        treeMap.fisrtKey();
        treeMap.lastKey();
        treeMap.lower(new Integer(2));
        
    }
}


TreeSet과 TreeMap의 Comparable, Comparator

Comparator와 Comparable:
TreeSet 및 TreeMap을 사용할 때, 사용자 정의 클래스를 저장할 경우, 정렬을 위해 Comparator 또는 Comparable을 구현해야 한다. Comparable은 클래스 자체에서 비교 로직을 구현하는 데 사용되고, Comparator는 외부에서 비교 로직을 제공하는 데 사용한다. < Generic> 에 들어가는 Integer, Double, String은 모두 Comparable 인터페이스를 구현하고 있기 때문에 TreeSet과 TreeMap에서 정렬이 가능하다.

import java.util.TreeSet;

class Person implements Comparable<Person> {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public int compareTo(Person otherPerson) {
        return Integer.compare(this.age, otherPerson.age);
    }

    // Getter methods, equals, hashCode, and other methods...

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + '}';
    }
}

public class TreeSetWithComparator {

    public static void main(String[] args) {
        TreeSet<Person> treeSet = new TreeSet<>();

        treeSet.add(new Person("Alice", 25));
        treeSet.add(new Person("Bob", 20));
        treeSet.add(new Person("Charlie", 30));

        for (Person person : treeSet) {
            System.out.println(person);
        }
    }
}

Properties

java.util.Properties 클래스는 키-값 쌍을 사용하여 속성 정보를 저장하는데 사용되는 클래스이다. 주로 설정 파일, 환경 변수, 애플리케이션의 구성 정보 등을 저장하는 데에 활용된다.

// 파일 입출력으로 사용
Properties properties = new Properties();

// 파일에서 속성 읽어오기
try (FileInputStream fileInputStream = new FileInputStream("config.properties")) {
    properties.load(fileInputStream);
} catch (IOException e) {
    e.printStackTrace();
}

// 속성 파일로 저장하기
try (FileOutputStream fileOutputStream = new FileOutputStream("config.properties")) {
    properties.store(fileOutputStream, "Configuration Properties");
} catch (IOException e) {
    e.printStackTrace();
}
// 시스템 프로퍼티 사용
Properties systemProperties = System.getProperties();
String javaVersion = systemProperties.getProperty("java.version");
// 일반 사용법
Properties config = new Properties();

// 속성 설정
config.setProperty("database.url", "jdbc:mysql://localhost:3306/mydb");
config.setProperty("database.user", "username");
config.setProperty("database.password", "password");

// 속성 읽기
String dbUrl = config.getProperty("database.url");
String dbUser = config.getProperty("database.user");
String dbPassword = config.getProperty("database.password");
profile
Programmer, who turns ideas into value

0개의 댓글