KineticMate
KineticMate
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
Week 120 — What are the differences between `HashSet` and `TreeSet`?
HashSet is a set which takes the elements in random order in O(1) time complexity while TreeSet is a set which maintains the sorted order of elements in O(log n) time complexity
6 replies
Week 120 — What are the differences between `HashSet` and `TreeSet`?
i may be writing nonsense and approaching the matter wrongly, but I have found that in the hash set the elements are arranged in a random order, while in the tree set they are in a fixed, ascending order
6 replies
Week 120 — What are the differences between `HashSet` and `TreeSet`?
Sets are collections of objects that are not allowed to contain duplicates with operations for adding and removing element as well as checking whether or not a set contains an element. HashSet is an unordered Set that can do these operations (adding, removing, checking for containment) in constant (O(1)) time assuming the element classes implement equals() and hashCode() properly. This means that having more elements in a HashSet doesn't make adding. removing or checking for existence take longer. TreeSet is a sorted Set where elements are sorted using a custom Comparator or using their compareTo method (if the element class implements compareTo). Keeping the elements sorted comes at the cost of the aforementioned set operations (add, remove, contains) need to be done with a time complexity of O(log(n)). Another Set implementation is LinkedHashSet which extends HashSet but keeps track of the insertion order meaning that it is possible to iterate over its elements in the order they have been added to the set. When executing the following code with someSet being a HashSet, the elements are not ordered (e.g. [here, some, Hello, text, World]). With TreeSet, the Strings are sorted lexicographically with uppercase letters before lowercase letters resulting in it printing [Hello, World, here, some, text]. With LinkedHashSet, the insertion order is kept and it prints [Hello, World, here, some, text].
Set<String> someSet = new HashSet<>();
//Set<String> someSet = new TreeSet<>();
//Set<String> someSet = new LinkedHashSet<>();
someSet.add("Hello");
someSet.add("World");
someSet.add("some");
someSet.add("text");
someSet.add("here");
System.out.println(someSet);
Set<String> someSet = new HashSet<>();
//Set<String> someSet = new TreeSet<>();
//Set<String> someSet = new LinkedHashSet<>();
someSet.add("Hello");
someSet.add("World");
someSet.add("some");
someSet.add("text");
someSet.add("here");
System.out.println(someSet);
6 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 3/30/2025 in #❓︱qotw-answers
Week 119 — What is the difference between a monolith and microservices?
Microservices are almost the exact opposite. They are inherently more complex, because compatibility needs to be carefully managed at the public interface level in order to support the different lifecycles of each service. Connectivity between the services can be a bottleneck and source of errors. Additional complexity then needs to be built into the service itself to counteract these hurdles. However, each service can be scaled and moved around independently. Since each one is more lightweight than a monolith, the result is an overall savings in resources, along with better characteristics in other areas, such as scalability, throughput, etc.
8 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 3/30/2025 in #❓︱qotw-answers
Week 119 — What is the difference between a monolith and microservices?
The advantage of a monolith is in its simplicity. All of the code to support a particular set of functionality lives together in the same codebase, running in the same process, so there are no issues with compatibility or connectivity between services. The biggest downside is that scaling is more difficult or resource-intensive. To support more requests or batch processes, more copies of the service have to be run behind some kind of load balancer. However, suppose the "customer maintenance" functionality is where most of the load is. In order to support the additional load, the full set of resources required to run the service must still be allocated for every copy, including CPU, memory, disk, database connections, etc.
8 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 3/30/2025 in #❓︱qotw-answers
Week 119 — What is the difference between a monolith and microservices?
On the other hand, microservices would decompose that functionality into multiple services that work together. In the "customer" service above, there might be separate services for customer maintenance, billing preferences, shipping preferences, etc. Each service would have its own artifact and runtime, and expose its own interface (e.g. a customer maintenance web endpoint, shipping preferences message queue, etc.).
8 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 3/30/2025 in #❓︱qotw-answers
Week 119 — What is the difference between a monolith and microservices?
Monoliths package all functionality into a single service. For instance, a "customer" service might expose all of the functionality needed to create and maintain customers, their contact info, billing preferences, shipping preferences, etc. It would typically be accessible through a single interface (such as a web endpoint, message broker, etc.).
8 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 3/30/2025 in #❓︱qotw-answers
Week 119 — What is the difference between a monolith and microservices?
Monoliths and microservices are two possible architectures for building web services. The differences between the two lie in how the functionality is organized and composed.
8 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 3/30/2025 in #❓︱qotw-answers
Week 119 — What is the difference between a monolith and microservices?
Monolith and Microservices are software architecture styles associated with structuring and deployment of code. All the logic in monolithic systems is grouped into one single codebase. The entire project needs to be redeployed even for a minor change in the codebase. The code is also very tightly coupled that leads to maintaining these applications very difficult as the project grows large. It's not all bad though. Since everything is in the same codebase, debugging and deploying these applications is easy. There are no additional network costs since the entire application runs as a single process and everything happens in memory. However logic in a microservice based systems is distributed across multiple services, where each service performs a specific task. These services may communicate with each through direct API calls or via messaging queues like kafka. Since the code is distributed, many teams can work parallely on each service and deploy them independently. This leads to faster development and removes tight coupling.
8 replies