lars
lars
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 5/11/2025 in #❓︱qotw-answers
Week 125 — How can one set the heap size of a Java application?
Why the need? We get OutOfMemoryError when the heap memory runs out. When this happens the JVM throws the OutOfMemoryError and if it is uncaught the program crashes. Check JVM heap settings To see how your JVM chooses defaults:
$ java -XX:+PrintFlagsFinal -version | grep HeapSize
$ java -XX:+PrintFlagsFinal -version | grep HeapSize
You’ll see values like:
InitialHeapSize = 268435456 # 256 MB (-Xms)
MaxHeapSize = 4294967296 # 4 GB (-Xmx)
InitialHeapSize = 268435456 # 256 MB (-Xms)
MaxHeapSize = 4294967296 # 4 GB (-Xmx)
These are set ergonomically based on your machine’s specs. Example
import java.util.ArrayList;
import java.util.List;

public class HeapStressTest {
public static void main(String[] args) {
List<byte[]> memoryHog = new ArrayList<>();
int count = 0;

try {
while (true) {
// Allocate 10 MB chunks
memoryHog.add(new byte[10 * 1024 * 1024]);
count++;
System.out.println("Allocated " + count * 10 + " MB");
Thread.sleep(100); // Slow it down a bit
}
} catch (OutOfMemoryError e) {
System.err.println("💥 OutOfMemoryError after allocating " + count * 10 + " MB");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
import java.util.ArrayList;
import java.util.List;

public class HeapStressTest {
public static void main(String[] args) {
List<byte[]> memoryHog = new ArrayList<>();
int count = 0;

try {
while (true) {
// Allocate 10 MB chunks
memoryHog.add(new byte[10 * 1024 * 1024]);
count++;
System.out.println("Allocated " + count * 10 + " MB");
Thread.sleep(100); // Slow it down a bit
}
} catch (OutOfMemoryError e) {
System.err.println("💥 OutOfMemoryError after allocating " + count * 10 + " MB");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
In this Example we keep allocating 10MB chunks of memory until we get the OutOfMemoryError. Solution We can set the initial as well as the max heap size by passing some VM options when we run the program. - -Xms : initial heap size - -Xmx : max heap size We can pass these options like this:
$ java -Xmx2g -Xms512m HeapStressTest
$ java -Xmx2g -Xms512m HeapStressTest
Or for more verbose GC info we can add this options as well
$ java -Xmx2g -Xms512m -XX:+PrintGCDetails HeapStressTest
$ java -Xmx2g -Xms512m -XX:+PrintGCDetails HeapStressTest
3 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 5/11/2025 in #❓︱qotw-answers
Week 125 — How can one set the heap size of a Java application?
By default, the JVM detects a suitable heap size given system and environment constraints but sometimes, developers may want to set it to a different value. For configuring the heap site, the most important option is the maximum heap size which can be set with the -Xmx argument. This argument must come before the main class or the -jar argument when calling the java command:
# run a JAR file with a maximum heap size of 1GB
java -Xmx1G -jar yourjar.jar

# run a class with a maximum heap size of 1GB
java -Xmx1G your.fully.qualified.MainClass
# run a JAR file with a maximum heap size of 1GB
java -Xmx1G -jar yourjar.jar

# run a class with a maximum heap size of 1GB
java -Xmx1G your.fully.qualified.MainClass
Similar to the maximum heap size, it is also possible to set an initial heap size. When the application starts, it will start with that heap size and allocate more memory if necessary until it reaches the maximum heap size.
# set minimum heap size to 100MB and run a JAR
java -Xms100M -jar yourjar.jar

# set both the initial heap size (100MB) and maximum heap size (1GB) when running a JAR
java -Xms100M -Xmx1G -jar yourjar.jar

# set both the initial and maximum heap size to the same value (1GB) to force it allocating that memory at the beginning
java -Xms1G -Xmx1G -jar yourjar.jar
# set minimum heap size to 100MB and run a JAR
java -Xms100M -jar yourjar.jar

# set both the initial heap size (100MB) and maximum heap size (1GB) when running a JAR
java -Xms100M -Xmx1G -jar yourjar.jar

# set both the initial and maximum heap size to the same value (1GB) to force it allocating that memory at the beginning
java -Xms1G -Xmx1G -jar yourjar.jar
3 replies
Week 124 — How can one read and write CSV files in Java?
It could be done using BufferedReader, FileReader for reading CSV And BufferedWriter, FileWriter for writing CSV
4 replies
Week 124 — How can one read and write CSV files in Java?
To write such a CSV file with Apache Commons CSV, one can call the printRecord on the CSVFormat class for every entry:
private CSVFormat format = CSVFormat.DEFAULT
.builder()
.setHeader("First name", "Last name", "Age")
.build();
private CSVFormat format = CSVFormat.DEFAULT
.builder()
.setHeader("First name", "Last name", "Age")
.build();
public void savePeopleApacheCommons(List<Person> people) throws IOException {
try(CSVPrinter printer = format.print(Files.newBufferedWriter(Path.of("people.csv")))) {
for(Person person : people) {
printer.printRecord(person.firstName(), person.lastName(), person.age());
}
}
}
public void savePeopleApacheCommons(List<Person> people) throws IOException {
try(CSVPrinter printer = format.print(Files.newBufferedWriter(Path.of("people.csv")))) {
for(Person person : people) {
printer.printRecord(person.firstName(), person.lastName(), person.age());
}
}
}
It can then be read using the CSVFormat.parse method:
public List<Person> readPeopleApacheCommons() throws IOException {
List<Person> people = new ArrayList<>();
try(BufferedReader br = Files.newBufferedReader(Path.of("people.csv"))){
for(CSVRecord entry : format.parse(reader)) {
people.add(entry.get("First name"), entry.get("Last name"), Integer.parseInt(entry.get("Age")));
}
return people;
}
}
public List<Person> readPeopleApacheCommons() throws IOException {
List<Person> people = new ArrayList<>();
try(BufferedReader br = Files.newBufferedReader(Path.of("people.csv"))){
for(CSVRecord entry : format.parse(reader)) {
people.add(entry.get("First name"), entry.get("Last name"), Integer.parseInt(entry.get("Age")));
}
return people;
}
}
4 replies
Week 124 — How can one read and write CSV files in Java?
Reading and writing CSV files is possible both using the standard libraries (e.g. java.io) and using external libraries. For example, we might want to save the following record in a CSV file and read it again:
record Person(String firstName, String lastName, int age) {}
record Person(String firstName, String lastName, int age) {}
This can be done using the JDK standard libraries by creating a Writer and saving it line by line:
public void savePeople(List<Person> people) throws IOException {
try(BufferedWriter bw = Files.newBufferedWriter(Path.of("people.csv"))) {
bw.write("First name,Last name,Age");
bw.newLine();

for(Person person : people) {
bw.write(person.firstName());
bw.write(",");
bw.write(person.lastName());
bw.write(",");
bw.write(String.valueOf(person.age()));
bw.newLine();
}
}
}
public void savePeople(List<Person> people) throws IOException {
try(BufferedWriter bw = Files.newBufferedWriter(Path.of("people.csv"))) {
bw.write("First name,Last name,Age");
bw.newLine();

for(Person person : people) {
bw.write(person.firstName());
bw.write(",");
bw.write(person.lastName());
bw.write(",");
bw.write(String.valueOf(person.age()));
bw.newLine();
}
}
}
To read a CSV file corresponding to the code before, the file can be read line by line and split by commas:
public List<Person> readPeople() throws IOException {
List<Person> people = new ArrayList<>();
try(BufferedReader br = Files.newBufferedReader(Path.of("people.csv"))){
br.readLine(); // skip header

String line;
while((line = br.readLine()) != null) {
String[] split = line.split(",");
if(split.length != 3) {
throw new IOException("invalid number of columns");
}
people.add(new Person(split[0], split[1], Integer.parseInt(split[2])));
}
}
return Collections.unmodifiableList(people);
}
public List<Person> readPeople() throws IOException {
List<Person> people = new ArrayList<>();
try(BufferedReader br = Files.newBufferedReader(Path.of("people.csv"))){
br.readLine(); // skip header

String line;
while((line = br.readLine()) != null) {
String[] split = line.split(",");
if(split.length != 3) {
throw new IOException("invalid number of columns");
}
people.add(new Person(split[0], split[1], Integer.parseInt(split[2])));
}
}
return Collections.unmodifiableList(people);
}
However, this code does not address the possibility of commas, quoting, line breaks or backslashes in the input. While it is possible to add validation for that, it is also possible to use external libraries for this task.
4 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 4/27/2025 in #❓︱qotw-answers
Week 123 — What is the difference between List.of() and Arrays.asList()?
Similar to List.of, List.copyOf creates an immutable List that is a copy of another List Since this is a copy, changing the original List doesn't modify the copy.
List<String> originalList = new ArrayList<>();
originalList.add("Hello");
originalList.add("World");

List<String> immutableCopy = List.copyOf(originalList);
System.out.println(immutableCopy.get(0));//Hello
//immutableCopy.remove(0);//UnsupportedOperationException
//immutableCopy.set(0, "Goodbye");//UnsupportedOperationException
//immutableCopy.add("return");//UnsupportedOperationException
originalList.set(1,"Java");
System.out.println(originalList);//[Hello, Java]
System.out.println(immutableCopy);//[Hello, World]
List<String> originalList = new ArrayList<>();
originalList.add("Hello");
originalList.add("World");

List<String> immutableCopy = List.copyOf(originalList);
System.out.println(immutableCopy.get(0));//Hello
//immutableCopy.remove(0);//UnsupportedOperationException
//immutableCopy.set(0, "Goodbye");//UnsupportedOperationException
//immutableCopy.add("return");//UnsupportedOperationException
originalList.set(1,"Java");
System.out.println(originalList);//[Hello, Java]
System.out.println(immutableCopy);//[Hello, World]
On the other hand, Collections.unmodifiableList creates an unmodifiable view on a List. While that view cannot be modified, changes to the backing List are propagated to the view:
List<String> backingList = new ArrayList<>();
backingList.add("Hello");
backingList.add("World");

List<String> unmodifiableView = Collections.unmodifiableList(backingList);
System.out.println(unmodifiableView.get(0));//Hello
//unmodifiableView.remove(0);//UnsupportedOperationException
//unmodifiableView.set(0, "Goodbye");//UnsupportedOperationException
//unmodifiableView.add("return");//UnsupportedOperationException
backingList.set(1,"Java");
System.out.println(unmodifiableView);//[Hello, Java]
System.out.println(backingList);//[Hello, Java]
List<String> backingList = new ArrayList<>();
backingList.add("Hello");
backingList.add("World");

List<String> unmodifiableView = Collections.unmodifiableList(backingList);
System.out.println(unmodifiableView.get(0));//Hello
//unmodifiableView.remove(0);//UnsupportedOperationException
//unmodifiableView.set(0, "Goodbye");//UnsupportedOperationException
//unmodifiableView.add("return");//UnsupportedOperationException
backingList.set(1,"Java");
System.out.println(unmodifiableView);//[Hello, Java]
System.out.println(backingList);//[Hello, Java]
3 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 4/27/2025 in #❓︱qotw-answers
Week 123 — What is the difference between List.of() and Arrays.asList()?
Java provides various factory methods for creating lists and other collections including List.of, Arrays.asList as well as List.copyOf and Collections.unmodifiableList. The List.of method creates a new list from the elements passed as arguments. The created list is immutable.
List<String> immutableList = List.of("Hello", "World");
System.out.println(immutableList.get(0));//Hello
//immutableList.remove(0);//UnsupportedOperationException
//immutableList.set(0, "Goodbye");//UnsupportedOperationException
//immutableList.add("return");//UnsupportedOperationException
List<String> immutableList = List.of("Hello", "World");
System.out.println(immutableList.get(0));//Hello
//immutableList.remove(0);//UnsupportedOperationException
//immutableList.set(0, "Goodbye");//UnsupportedOperationException
//immutableList.add("return");//UnsupportedOperationException
On the other hand, Arrays.asList creates a List view from an array. Changes to the List are reflected in the array and vice-versa. Since arrays are not resizable, it is not possible to add or remove elements.
String[] backingArray = {"Hello", "World"};
List<String> arrayView = Arrays.asList(backingArray);
System.out.println(arrayView.get(0));//Hello
//arrayView.remove(0);//UnsupportedOperationException
arrayView.set(0, "Goodbye");
backingArray[1] = "Simulation";
//arrayView.add("return");//UnsupportedOperationException
System.out.println(arrayView);//[Goodbye, Simulation]
System.out.println(Arrays.toString(backingArray));//[Goodbye, Simulation]
String[] backingArray = {"Hello", "World"};
List<String> arrayView = Arrays.asList(backingArray);
System.out.println(arrayView.get(0));//Hello
//arrayView.remove(0);//UnsupportedOperationException
arrayView.set(0, "Goodbye");
backingArray[1] = "Simulation";
//arrayView.add("return");//UnsupportedOperationException
System.out.println(arrayView);//[Goodbye, Simulation]
System.out.println(Arrays.toString(backingArray));//[Goodbye, Simulation]
3 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 4/20/2025 in #❓︱qotw-answers
Week 122 — How can one specify a charset when reading from/writing to a text file?
To write data to a text file encoded with a given charset, the JDK provides overloads for many methods that behave differently for charsets:
try(BufferedWriter writer = Files.newBufferedWriter(Path.of("utfFile.txt"), StandardCharsets.UTF_8)) {
writer.write("Hello World");
writer.newLine();
writer.write("\uD83D\uDCBB");//unicode escapes for an emoji
}
try(BufferedWriter writer = Files.newBufferedWriter(Path.of("utfFile.txt"), StandardCharsets.UTF_8)) {
writer.write("Hello World");
writer.newLine();
writer.write("\uD83D\uDCBB");//unicode escapes for an emoji
}
This file can then be read using the same charset:
try(BufferedReader reader = Files.newBufferedReader(Path.of("utfFile.txt"), StandardCharsets.UTF_8)) {
reader.lines().forEach(System.out::println);
}
try(BufferedReader reader = Files.newBufferedReader(Path.of("utfFile.txt"), StandardCharsets.UTF_8)) {
reader.lines().forEach(System.out::println);
}
If the console is able to display emojis and configured correctly using UTF-8, executing the two code snippets after each other should display Hello World and the 💻 emoji. However, if the file is attempted to be read using a charset that doesn't match, the output can get messed up:
try(BufferedReader reader = Files.newBufferedReader(Path.of("utfFile.txt"), StandardCharsets.UTF_16)) {
reader.lines().forEach(System.out::println);
}
try(BufferedReader reader = Files.newBufferedReader(Path.of("utfFile.txt"), StandardCharsets.UTF_16)) {
reader.lines().forEach(System.out::println);
}
As UTF-8 and UTF-16 don't use the same representations of characters, the output consists of characters that have little in common with the original text. When attemping to read the text file using ASCII instead, an exception is thrown because the emoji contains characters that are not valid ASCII:
try(BufferedReader reader = Files.newBufferedReader(Path.of("utfFile.txt"), StandardCharsets.US_ASCII)) {
reader.lines().forEach(System.out::println); // MalformedInputException
}
try(BufferedReader reader = Files.newBufferedReader(Path.of("utfFile.txt"), StandardCharsets.US_ASCII)) {
reader.lines().forEach(System.out::println); // MalformedInputException
}
3 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 4/20/2025 in #❓︱qotw-answers
Week 122 — How can one specify a charset when reading from/writing to a text file?
When writing a file, it is stored as binary data on the file system. To store text files, the textual content has to converted to a binary format before writing to the file and converted back after reading. The used character encoding/charset decides how that process is performed. When converting between strings and binary data, the same charset should be used both converting the text to binary and for converting it back. One such charset is ASCII which represents each character using only 7 bits at the cost of only being able to represent a few characters (typically aligned so that each character actually needs one byte). In contrast to that, unicode allows storing more characters where different characters may require a different amount of space depending on the character used. It comes in different flavors like UTF-8 (which requires at least 8 bits = 1 byte to store each character) or UTF-16 (requires at least 16 bits = 2 bytes to store each character). Letters that can be represented using ASCII are represented the exact same way in UTF-8 with the first bit being set to 0. To indicate multiple bytes needed for a "code point" the first bits are set to 1. Unicode also supports many other things like combining (joining) multiple code points to a single displayable character. Java provides the java.nio.charset.Charset class to represent charsets and includes the java.nio.charset.StandardCharsets class with some commonly used charsets like US_ASCII and UTF_8.
3 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 4/13/2025 in #❓︱qotw-answers
Week 121 — What mechanisms do the Java standard libraries provide for sorting?
The Java standard libraries provide several mechanisms for sorting: 1. Arrays.sort() Used for sorting arrays. Works for primitive types (e.g., int[]) and objects (e.g., String[], Integer[]). Overloads allow custom sorting via Comparator. ex; Arrays.sort(array); Arrays.sort(array, Comparator.reverseOrder()); 2. Collections.sort() Used for sorting List collections (e.g., ArrayList). Can sort using natural order or with a custom Comparator. ex; Collections.sort(list); Collections.sort(list, comparator); 3. List.sort() (Java 8+) Direct method on List interface using a lambda or Comparator. ex; list.sort(Comparator.comparing(Person::getName)); 4. Streams API (Java 8+) Used for sorting streams, especially in functional-style processing. ex; list.stream().sorted().collect(Collectors.toList()); list.stream().sorted(Comparator.comparing(...)); These mechanisms use efficient sorting algorithms internally, like TimSort for object sorting.
10 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 4/13/2025 in #❓︱qotw-answers
Week 121 — What mechanisms do the Java standard libraries provide for sorting?
Once the comparison logic is defined, it can be used in a number of ways.... COLLECTIONS Many classes in the Java Collections framework understand classes that implement Comparable, and will use the "natural ordering" exposed by that interface. Those same collection classes will often allow a separate Comparator implementation to be supplied in the constructor to use for ordering. For instance,TreeSet expects objects added to it to implement Comparable, unless a separate Comparator has been supplied to the constructor. The List interface defines a sort(Comparator) method, which also allows for a null parameter, in which case the "natural ordering" is used. ARRAYS The Collections framework also provides the Arrays class, which contains a number of static methods for working with arrays, including comparison, sorting, and searching operations. Some of the methods accept a Comparator, which can be null to trigger the use of "natural ordering" (similar to the List::sort(Comparator) method). Some require that the objects implement the Comparable interface. Note that Arrays also provides methods for comparing, sorting, and searching arrays of numeric primitives, which are inherently comparable.
10 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 4/13/2025 in #❓︱qotw-answers
Week 121 — What mechanisms do the Java standard libraries provide for sorting?
The foundation of sorting comes down to two interfaces: java.lang.Comparable<T> and java.util.Comparator<T> Comparable is implemented by classes that want to have an intrinsic comparison order between objects of that class. For instance, a Person class might implement Comparable<Person> that sorts Person objects by last name, then first name:
class Person implements Comparable<Person> {
// ...
@Override
public int compareTo(final Person o) {
int lnCompare = lastName.compareTo(o.lastName);
if (lnCompare == 0) {
return firstName.compareTo(o.firstName);
}
return lnCompare;
}
}
class Person implements Comparable<Person> {
// ...
@Override
public int compareTo(final Person o) {
int lnCompare = lastName.compareTo(o.lastName);
if (lnCompare == 0) {
return firstName.compareTo(o.firstName);
}
return lnCompare;
}
}
Comparator provides a mechanism for creating external comparison ordering operations. These are often implemented as lambdas, but do not have to be. To continue the Person example, another class can be created to order those objects by years of service:
public class Person implements Comparable<Person> {
public static Comparator<Person> SORT_BY_YEARS_OF_SERVICE = (left, right) -> {
final float diff = left.yearsOfService - right.yearsOfService;
if (diff == 0) {
return 0;
}
return diff > 0 ? 1 : -1;
};
// ...
}
public class Person implements Comparable<Person> {
public static Comparator<Person> SORT_BY_YEARS_OF_SERVICE = (left, right) -> {
final float diff = left.yearsOfService - right.yearsOfService;
if (diff == 0) {
return 0;
}
return diff > 0 ? 1 : -1;
};
// ...
}
10 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 4/13/2025 in #❓︱qotw-answers
Week 121 — What mechanisms do the Java standard libraries provide for sorting?
There are a number of different mechanisms for sorting objects and values in a Java program. Which one to use depends on the data structure being used.
10 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 4/13/2025 in #❓︱qotw-answers
Week 121 — What mechanisms do the Java standard libraries provide for sorting?
Similarly, TreeSet can be used to create a Set which does not allow duplicates and is always sorted.
SortedSet<String> alwaysSortedSet = new TreeSet<>(List.of("Hello", "World", " - ", "This", "is", "an", "example", "array", "to", "be", "sorted") /*, String.CASE_INSENSITIVE_ORDER*/);

alwaysSortedSet.add(".");
alwaysSortedSet.addAll(List.of("New entries are put 'in the right spot' automatically".split(" ")));

System.out.println(alwaysSortedSet);// [ - , 'in, ., Hello, New, This, World, an, are, array, automatically, be, entries, example, is, put, right, sorted, spot', the, to]
SortedSet<String> alwaysSortedSet = new TreeSet<>(List.of("Hello", "World", " - ", "This", "is", "an", "example", "array", "to", "be", "sorted") /*, String.CASE_INSENSITIVE_ORDER*/);

alwaysSortedSet.add(".");
alwaysSortedSet.addAll(List.of("New entries are put 'in the right spot' automatically".split(" ")));

System.out.println(alwaysSortedSet);// [ - , 'in, ., Hello, New, This, World, an, are, array, automatically, be, entries, example, is, put, right, sorted, spot', the, to]
10 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 4/13/2025 in #❓︱qotw-answers
Week 121 — What mechanisms do the Java standard libraries provide for sorting?
When elements are produced in some way and need to be consumed in their natural order (according to Comparable) or according to a custom Comparable), PriorityQueue is based on a heap and can be used which ensures that the "smallest" element is consumed first.
Queue<String> heap = new PriorityQueue<>();//or new PriorityQueue<>(String.CASE_INSENSITIVE_ORDER); to use a custom comparator
for(String s : List.of("Hello", "World", " - ", "This", "is", "an", "example", "array", "to", "be", "sorted")) {
heap.add(s);
}

//prints the Strings in lexicographical order
while(!heap.isEmpty()) {
System.out.println(heap.poll());
}
Queue<String> heap = new PriorityQueue<>();//or new PriorityQueue<>(String.CASE_INSENSITIVE_ORDER); to use a custom comparator
for(String s : List.of("Hello", "World", " - ", "This", "is", "an", "example", "array", "to", "be", "sorted")) {
heap.add(s);
}

//prints the Strings in lexicographical order
while(!heap.isEmpty()) {
System.out.println(heap.poll());
}
10 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 4/13/2025 in #❓︱qotw-answers
Week 121 — What mechanisms do the Java standard libraries provide for sorting?
In addition to arrays, Lists can be sorted using the Collections.sort method.
List<String> listToBeSorted = new ArrayList<>(List.of("Hello", "World", " - ", "This", "is", "an", "example", "array", "to", "be", "sorted"));
Collections.sort(listToBeSorted);
System.out.println(listToBeSorted); // [ - , Hello, This, World, an, array, be, example, is, sorted, to]

Collections.sort(listToBeSorted, String.CASE_INSENSITIVE_ORDER);
System.out.println(listToBeSorted); // [ - , an, array, be, example, Hello, is, sorted, This, to, World]
List<String> listToBeSorted = new ArrayList<>(List.of("Hello", "World", " - ", "This", "is", "an", "example", "array", "to", "be", "sorted"));
Collections.sort(listToBeSorted);
System.out.println(listToBeSorted); // [ - , Hello, This, World, an, array, be, example, is, sorted, to]

Collections.sort(listToBeSorted, String.CASE_INSENSITIVE_ORDER);
System.out.println(listToBeSorted); // [ - , an, array, be, example, Hello, is, sorted, This, to, World]
10 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 4/13/2025 in #❓︱qotw-answers
Week 121 — What mechanisms do the Java standard libraries provide for sorting?
Objects that have a natural order can choose to implement Comparable which allows them to define a compareTo method specifying how these objects should be ordered by default (unless a custom Comparator is specified). For example, Strings are naturally ordered lexicographically so it is not necessary to provide a custom Comparator when that order is wanted.
String[] stringsToBeSorted = {"Hello", "World", " - ", "This", "is", "an", "example", "array", "to", "be", "sorted"};
Arrays.sort(stringsToBeSorted);
System.out.println(Arrays.toString(stringsToBeSorted));// [ - , Hello, This, World, an, array, be, example, is, sorted, to]

Comparator<String> caseInsensitiveComparator = String.CASE_INSENSITIVE_ORDER;
Arrays.sort(stringsToBeSorted, caseInsensitiveComparator);
System.out.println(Arrays.toString(stringsToBeSorted));// [ - , an, array, be, example, Hello, is, sorted, This, to, World]
String[] stringsToBeSorted = {"Hello", "World", " - ", "This", "is", "an", "example", "array", "to", "be", "sorted"};
Arrays.sort(stringsToBeSorted);
System.out.println(Arrays.toString(stringsToBeSorted));// [ - , Hello, This, World, an, array, be, example, is, sorted, to]

Comparator<String> caseInsensitiveComparator = String.CASE_INSENSITIVE_ORDER;
Arrays.sort(stringsToBeSorted, caseInsensitiveComparator);
System.out.println(Arrays.toString(stringsToBeSorted));// [ - , an, array, be, example, Hello, is, sorted, This, to, World]
10 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 4/13/2025 in #❓︱qotw-answers
Week 121 — What mechanisms do the Java standard libraries provide for sorting?
Arrays can be sorted using the Arrays.sort methods:
int[] arrayToBeSorted = {51,61,561,581,65,84,53,12,86,12,213,87,31,48};
Arrays.sort(arrayToBeSorted);
System.out.println(Arrays.toString(arrayToBeSorted));//[12, 12, 31, 48, 51, 53, 61, 65, 84, 86, 87, 213, 561, 581]
int[] arrayToBeSorted = {51,61,561,581,65,84,53,12,86,12,213,87,31,48};
Arrays.sort(arrayToBeSorted);
System.out.println(Arrays.toString(arrayToBeSorted));//[12, 12, 31, 48, 51, 53, 61, 65, 84, 86, 87, 213, 561, 581]
Sorting primitive types typically happens in ascending order of their values but when sorting arbitrary objects, one needs to decide how these should be sorted which can be done using a Comparator that compares two objects and returns - a positive value if the first object is considered greater than the second object - a negative value if the first object is considered smaller than the second object - zero if both objects are equal
10 replies
Week 120 — What are the differences between `HashSet` and `TreeSet`?
In addition to Set, the TreeSet implements both SortedSet and NavigableSet. SortedSet guarantees the sort and iteration order of its elements. The order is determined by the elements' natural order, or by a Comparator provided at construction time. NavigableSet defines additional methods to navigate through the elements in the Set. Because the elements are in a predictable order, the navigation methods also behave predictably.
6 replies
Week 120 — What are the differences between `HashSet` and `TreeSet`?
HashSet & TreeSet are both implementations of the java.util.Set interface. Like all implementations of Set, only unique elements are allowed. However, a TreeSet also provides predictable iteration order and other navigation primitives.
6 replies