๐Collections.sort()
Collections.sort()๋ List๋ฅผ ์ค๋ฆ์ฐจ์(์์ฐ ์์)์ผ๋ก ์ ๋ ฌํฉ๋๋ค.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(2);
numbers.add(8);
numbers.add(1);
Collections.sort(numbers);
System.out.println("์ค๋ฆ์ฐจ์ ์ ๋ ฌ: " + numbers);
}
}
์ค๋ฆ์ฐจ์ ์ ๋ ฌ: [1, 2, 5, 8]
๐List.sort()
Collections.sort()์ ๋น์ทํ์ง๋ง, ๋ฆฌ์คํธ์ ์ง์ ์ ๋ ฌ ๋ฉ์๋๋ฅผ ํธ์ถํ ์ ์์ต๋๋ค.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(2);
numbers.add(8);
numbers.add(1);
numbers.sort((a, b) -> b - a);
System.out.println("๋ด๋ฆผ์ฐจ์ ์ ๋ ฌ: " + numbers);
}
}
์ถ๋ ฅ
๋ด๋ฆผ์ฐจ์ ์ ๋ ฌ: [8, 5, 2, 1]
๐์คํธ๋ฆผ ์ ๋ ฌ
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Charlie");
names.add("Alice");
names.add("Bob");
List<String> sortedNames = names.stream()
.sorted()
.collect(Collectors.toList());
System.out.println("์คํธ๋ฆผ ์ ๋ ฌ: " + sortedNames);
}
}
์ถ๋ ฅ
์คํธ๋ฆผ ์ ๋ ฌ: [Alice, Bob, Charlie]