This is not like Collections.sort() where the parameter reference gets sorted. In this case you just get a sorted stream that you need to collect and assign to another variable eventually:

CopyList result = list.stream().sorted((o1, o2)->o1.getItem().getValue().
                                   compareTo(o2.getItem().getValue())).
                                   collect(Collectors.toList());

You've just missed to assign the result

Answer from Jan B. on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › stream-sorted-comparator-comparator-method-java
Stream sorted (Comparator comparator) method in Java - GeeksforGeeks
December 26, 2025 - In Java, the Stream.sorted(Comparator comparator) method sorts the elements of a stream based on a provided Comparator and returns a new sorted stream.
🌐
Baeldung
baeldung.com › home › java › java – powerful comparison with lambdas
Java – Powerful Comparison with Lambdas | Baeldung
January 8, 2024 - sorted() – sorts the elements of a Stream using natural ordering; the element class must implement the Comparable interface.
🌐
Medium
medium.com › @AlexanderObregon › javas-stream-sorted-method-explained-52b9b25e9f84
Java’s Stream.sorted() Method Explained | Medium
December 26, 2024 - This example filters the stream to include only strings, preventing runtime errors caused by comparing incompatible types. Sorting a stream with duplicate elements works fine, but if unique values are needed, use the distinct() method before sorting. ... import java.util.Arrays; import java.util.List; public class DuplicatesExample { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(7, 2, 5, 7, 9, 2); numbers.stream() .distinct() // Remove duplicates .sorted() .forEach(System.out::println); } }
🌐
HowToDoInJava
howtodoinjava.com › home › java 8 › java stream sorted() example with/without comparator
Java Stream sorted() Example with/without Comparator
August 23, 2023 - Learn to use Java stream sorted() to sort a stream of elements in the natural order or according to the a Comparator or a Lambda Expression.
🌐
Medium
medium.com › @coffeeandtips.tech › using-comparator-comparing-to-sort-java-stream-a6e0302dce1a
Using Comparator.comparing to sort Java Stream | by Coffee and Tips | Medium
December 2, 2023 - The Comparator.comparing interface is a powerful tool to perform the sorting of Streams in Java. Its flexibility, ascending and descending sorting capabilities, support for multiple criteria, and efficient execution make it a valuable choice ...
🌐
SWTestAcademy
swtestacademy.com › home › java streams comparators with examples
Java Streams Comparators with Examples
October 10, 2021 - Let’s start with some sorting examples. We can use the Comparator interface’s naturalOrder() and reverseOrder() method to sort the elements of a stream in Ascending and Descending order.
🌐
Stack Abuse
stackabuse.com › java-8-how-to-sort-list-with-stream-sorted
Java 8 – How to Sort List with Stream.sorted()
July 21, 2021 - In this tutorial, we've covered everything you need to know about the Stream.sorted() method. We've sorted Comparable integers and Strings, in ascending and descending order, as well as used a built-in Comparator for custom objects.
Find elsewhere
🌐
Mkyong
mkyong.com › home › java8 › java 8 – how to sort list with stream.sorted()
Java 8 - How to sort list with stream.sorted() - Mkyong.com
March 8, 2019 - package com.mkyong.sorted; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; public class StreamApplication { public static void main(String[] args) { List<String> list = Arrays.asList("9", "A", "Z", "1", "B", "Y", "4", "a", "c"); /* List<String> sortedList = list.stream() .sorted((o1,o2)-> o2.compareTo(o1)) .collect(Collectors.toList()); */ List<String> sortedList = list.stream() .sorted(Comparator.reverseOrder()) .collect(Collectors.toList()); sortedList.forEach(System.out::println); } }
🌐
Medium
medium.com › @playwithjava › sorting-java-stream-elements-ec4b75942799
Sorting Java Stream elements.. Comparator is FucntionaInterface, it… | by Playwithjava | Medium
August 21, 2023 - Stream<T> sorted(Comparator<? super T> comparator) Returns a stream consisting of the elements of this stream, sorted according to the provided Comparator.
🌐
Medium
rameshfadatare.medium.com › java-stream-sorted-method-with-examples-84c7ebf7d056
Java Stream sorted() Method with Examples | by Ramesh Fadatare | Medium
September 26, 2024 - When a comparator is provided, the elements are sorted according to the order defined by the comparator. To demonstrate the basic usage of sorted() with natural order, we will create a Stream of integers and sort them. import java.util.stre...
🌐
HowToDoInJava
howtodoinjava.com › home › java 8 › sorting a stream by multiple fields in java
Sorting a Stream by Multiple Fields in Java - Group by sort example
March 10, 2022 - //first name comparator Comparator<Employee> compareByFirstName = Comparator.comparing( Employee::getFirstName ); //last name comparator Comparator<Employee> compareByLastName = Comparator.comparing( Employee::getLastName ); //Compare by first name and then last name (multiple fields) Comparator<Employee> compareByFullName = compareByFirstName.thenComparing(compareByLastName); //Using Comparator - pseudo code list.stream().sorted( comparator ).collect(); Given below is an example of using thenComparing() to create Comparator which is capable of sorting the employees’ list by their first name
🌐
ConcretePage
concretepage.com › java › jdk-8 › java-8-stream-sorted-example
Java Stream sorted()
super T&gt comparator): Here we create an instance of Comparator using lambda expression. We can sort the stream elements in ascending and descending order.
🌐
TutorialsPoint
tutorialspoint.com › java-program-to-sort-string-stream-with-reversed-comparator
Java program to sort string stream with reversed comparator
Using the stream() method, we sort the list using the reversed comparator and display the results. ... import java.util.Arrays; import java.util.Comparator; import java.util.List; public class Demo { public static void main(String[] args) { List<String> list = Arrays.asList("Tom", "Jack", "Ryan", ...
🌐
Reddit
reddit.com › r/learnjava › it seems that comparator doesn't work on java stream, while it works with method collections.sort
r/learnjava on Reddit: It seems that Comparator doesn't work on java stream, while it works with method Collections.sort
March 14, 2024 -

Good morning everyone!

I was making the code for this method called ordersWithStatus(). The method should return informations about the orders. Such method returns a String obtained by concatenating all orders satisfying the criteria:

  1. Only orders with a given status passed by argument to the method

  2. The orders have to be sorted by: restaurant name, customer's first name, customer's last name, delivery time.

I don't understand why the method using the stream (the commented one) doesn't work, but the other one using Collections.sort() works. Expected: Napoli, Judi Dench : (19:00): M6->1 Napoli, Ralph Fiennes : (19:00): M1->2 M6->1 But was: Napoli, Ralph Fiennes : (19:00): M1->2 M6->1 Napoli, Judi Dench : (19:00): M6->1 I noted that using the stream, it seems that the method doesn't sort the output, it prints Ralph Fiennes first and then Judi Dench. What am I doing wrong with the stream? Could you please help me ?

Here is my code:

	/**
	 * Retrieve all order with a given status with all the relative details in text format.
	 * The list is sorted by name of restaurant, name of the customer, and delivery time.
	 * @param status the status to be matched
	 * @return textual representation of orders
	 */
	public String ordersWithStatus(OrderStatus status) {
	/* 	
		Set<String> outputSet = this.orders.stream()
		.filter(o->o.getStatus()==status)
		.sorted( Comparator.comparing(Order::getRestaurantName)
		.thenComparing(Order::getCustomerName1)
		.thenComparing(Order::getCustomerName2)
		.thenComparing(Order::getTime ))
		.map(Order::toString)
		.collect( Collectors.toSet() );

		String output = "";

		for (String order : outputSet){
			output+=order;
		}
		return output;
*/		
		// Pulling out each comparision step into a local reference
		Comparator<Order> byRestaurantName = (o1, o2) -> o1.getRestaurantName().
		compareTo(o2.getRestaurantName());
		
		Comparator<Order> byCustomer1name = (o1, o2) -> o1.getCustomerName1().
		compareTo(o2.getCustomerName1());
		
		Comparator<Order> byCustomer2name = (o1, o2) -> o1.getCustomerName2().
		compareTo(o2.getCustomerName2());
		
		Comparator<Order> byTime = (o1, o2) -> o1.getTime().
		compareTo(o2.getTime());
		
		List<Order> tempOrders = this.orders.stream().
		filter(o->o.getStatus()==status).
		collect(Collectors.toList());
		
		Collections.sort(tempOrders,
		 	byRestaurantName
			.thenComparing(byCustomer1name)
			.thenComparing(byCustomer2name)
			.thenComparing(byTime));

		String res = "";
		// for each order in the sorted orders list
		for (Order order : tempOrders){
			res+=order.toString();
		}

		return res;
	}
Top answer
1 of 2
2
Edit: I found what was the problem! Apparently collecting into a set, breaks the order
2 of 2
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › stream › Stream.html
Stream (Java Platform SE 8 )
October 20, 2025 - Returns a stream consisting of the elements of this stream, sorted according to the provided Comparator. For ordered streams, the sort is stable.
🌐
Medium
medium.com › geekculture › java-stream-sorted-3771e92f2899
Java Stream: Sorted | Geek Culture
June 15, 2022 - The Comparator class provides criteria for the most common types as long as custom ones. ... //1 List<String> namesList = namesList .stream() .sorted() .collect(Collectors.toList());//2 List<User> userList = userList .stream() .sorted(Compa...
🌐
W3Schools
w3schools.com › java › java_advanced_sorting.asp
Java Advanced Sorting (Comparator and Comparable)
It is easier to use the Comparable interface when possible, but the Comparator interface is more powerful because it allows you to sort any kind of object even if you cannot change its code. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
🌐
amitph
amitph.com › home › java › sorting collections with java streams api
Sorting Collections with Java Streams API - amitph
November 22, 2024 - We used a Java Lambda expression-based Comparator implementation to sort a collection of objects. In the end, we collect the sorted objects in a List. By default, both Java Stream sorted() methods sort the elements in the forward or ascending order.