PriorityQueue(우선순위 큐)

일반 적인 큐의 구조와 동일하나 데이터가 들어온 순서대로 나가는 것이 오름차순으로 따라 데이터가 나가는 자료구조

시간 복잡도 : O(NlogN)

 

import java.util.PriorityQueue;

public class Main {
    public static void main(String[] args) {
        PriorityQueue<Integer> desc = new PriorityQueue<>();
        desc.add(3);desc.add(5);desc.add(2);desc.add(1);desc.add(4);
        
        while (desc.size() > 0){
            System.out.print(desc.poll());  // 1 2 3 4 5 출력됨
        }
    }
 }

 

Collections.reverseOrder() 를 사용하여 내림차순으로 도 사용가능 

import java.util.Collections;
import java.util.PriorityQueue;

public class Main {
    public static void main(String[] args) {
        PriorityQueue<Integer> asc = new PriorityQueue<>(Collections.reverseOrder());
        asc.add(3);asc.add(5);asc.add(2);asc.add(1);asc.add(4);

        System.out.println(asc);
        while (asc.size() > 0){
            System.out.print(asc.poll());  //5 4 3 2 1 출력
        }
    }
}

 

'Java > Class & method' 카테고리의 다른 글

replace  (0) 2022.12.20

replace()  :  특정 문자열을 지정한 문자 값으로 변환 해주는 메서드

public class Main {
    public static void main(String[] args) {
        String str = "HEllO";
        System.out.println(str.replace("l","L"));  // 타겟 "L" 변환 대상 "L"
        //l이 L 로 변환 되어 "HELLO" 출력 됨
    }
}

 

replaceFirst()  :  특정 문자열 중 첫번째것 지정한 문자 값으로 변환 해주는 메서드

public class Main {
    public static void main(String[] args) {
        String str = "hello hello hello";
        System.out.println(str.replaceFirst("hello","HELLO"));  //  처음 hello 만 HELLO로 변환
    }
}

 

replaceAll() : 정규표현식으로 변환이 가능한 메서드

public class Main {
    public static void main(String[] args) {
        String str = "abcd ABCD 가나다라 1234 !@#$";
        System.out.println(str.replaceAll("[a-z]",""));  // 타겟 정규식 "(영어)소문자" 변환 대상 ""
        //모든 소문자 제거 후 출력
        System.out.println(str.replaceAll("[A-Z]",""));  // 타겟 정규식 "(영어)대문자" 변환 대상 ""
        //모든 대문자 제거 후 출력
        System.out.println(str.replaceAll("[A-z]",""));  // 타겟 정규식 "(영어)모든문자" 변환 대상 ""
        //모든 영문자 제거 후 출력
        System.out.println(str.replaceAll("[\\uAC00-\\uD7A3]",""));  // 타겟 정규식 "한국어" 변환 대상 ""
        //모든 한국어 제거 후 출력(유니코드)
        System.out.println(str.replaceAll("[0-9]",""));  // 타겟 정규식 "모든숫자" 변환 대상 ""
        //숫자가 전부 제거 후 출력 or \\d 로도 가능
        System.out.println(str.replaceAll("[^0-9]",""));  // 타겟 정규식 "숫자를 뺀 모두 " 변환 대상 ""
        //숫자만 남기고 전부 제거 후 출력  or \\D 로도 가능
        System.out.println(str.replaceAll("[\\s]",""));  // 타겟 정규식 "공백 " 변환 대상 ""
        //공백 제거 후 출력
        System.out.println(str.replaceAll("[\\S]",""));  // 타겟 정규식 "숫자를 뺀 모두 " 변환 대상 ""
        //공백만 남기고 전부 제거 후 출력
        System.out.println(str.replaceAll("[ab][c]",""));  // 타겟 정규식 "a나b를 중에 c가 조합된 문자 " 변환 대상 ""
        // bc 제거 후 출력
    }
}

이외에도 다양한 정규식 들이 있다.(추후 추가 예정)

'Java > Class & method' 카테고리의 다른 글

PriorityQueue(우선순위 큐)  (0) 2022.12.22

+ Recent posts