Print
카테고리: [ Development ]
조회수: 1474

1. 개요

자바 언어에서 배열(Array)을 정렬하는 방법이다. Arrays.sort 를 사용한다.


2. 숫자 정렬

import java.util.Arrays;

public class ArraySort {
    public static void main(String[] args) {
        int nums[] = { 13, 47, 55, 61, 99, 45 };

        for ( int n : nums ) {
            System.out.println(n);
        }

        Arrays.sort(nums);

        System.out.println("After sort ->");

        for ( int n : nums ) {
            System.out.println(n);
        }
    }
}

결과는 다음과 같다.

13
47
55
61
99
45
After sort ->
13
45
47
55
61
99

3. 숫자 역정렬 (Reverse)

import java.util.Arrays;
import java.util.Collections;

public class ArraySort {
    public static void main(String[] args) {
        int nums[] = { 13, 47, 55, 61, 99, 45 };

        for ( int n : nums ) {
            System.out.println(n);
        }

        Arrays.sort(nums);

        System.out.println("After sort ->");

        for ( int n : nums ) {
            System.out.println(n);
        }

        Integer[] numInt = Arrays.stream(nums).boxed().toArray(Integer[]::new);
        Arrays.sort(numInt, Collections.reverseOrder());

        System.out.println("After reverse sort ->");

        for ( Integer n : numInt ) {
            System.out.println(n);
        }
    }
}

결과는 다음과 같다.

13
47
55
61
99
45
After sort ->
13
45
47
55
61
99
After reverse sort ->
99
61
55
47
45
13

4. 문자 정렬

import java.util.Arrays;

public class ArraySort {
    public static void main(String[] args) {
        String strs[] = { "Apple", "Dell", "Gateway", "Sambo", "Daewoo" };

        for ( String s : strs ) {
            System.out.println(s);
        }

        Arrays.sort(strs);

        System.out.println("After sort ->");

        for ( String s : strs ) {
            System.out.println(s);
        }
    }
}

결과는 다음과 같다.

Apple
Dell
Gateway
Sambo
Daewoo
After sort ->
Apple
Daewoo
Dell
Gateway
Sambo

5. 문자 역정렬 (Reverse)

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ArraySort {
    public static void main(String[] args) {        
        String strs[] = { "Apple", "Dell", "Gateway", "Sambo", "Daewoo" };

        for ( String s : strs ) {
            System.out.println(s);
        }

        Arrays.sort(strs);

        System.out.println("After sort ->");

        for ( String s : strs ) {
            System.out.println(s);
        }

        List strList = new ArrayList(Arrays.asList(strs));
        Collections.reverse(strList);

        System.out.println("After reverse sort ->");

        String[] sortedStrs = strList.toArray(new String[strList.size()]);

        for ( String s : sortedStrs ) {
            System.out.println(s);
        }
    }
}

결과는 다음과 같다.

Apple
Dell
Gateway
Sambo
Daewoo
After sort ->
Apple
Daewoo
Dell
Gateway
Sambo
After reverse sort ->
Sambo
Gateway
Dell
Daewoo
Apple