Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

java 8  RSS feed

 
logavani govindaraj
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How will you sort a list of string using Java 8 lambda expression?

Regards...
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 15860
80
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch.

Have you tried answering this question yourself? If yes, then please show us what you tried. If you couldn't find out how to do it, then where exactly did you get stuck?

Some hints: Call stream() on a List to get a stream.
Look at the API documentation of interface java.util.stream.Stream. It has a method that is useful for sorting the content of a stream.
To convert the result back to a List, you have to collect the results. Look at the API docs of interface Stream again to find out what method you can use there. There's also a useful class java.util.stream.Collectors from which you'll want to use something.

Try to implement this yourself, and then show us what you came up with. The best way to learn is to discover it for yourself!
 
Pierre-Yves Saumont
Author
Ranch Hand
Posts: 98
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No need to use Stream:



But this is not optimal. The optimal version uses a method reference instead of a lambda:

 
Paul Clapham
Sheriff
Posts: 22185
38
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You don't even need the method reference:

 
Campbell Ritchie
Sheriff
Posts: 53750
127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The question does say using a lambda. Now, we all can see that has fallen foul of what not how, but maybe somebody told OP to use a λ. Or it is a challenge.
 
Rob Spoor
Sheriff
Posts: 20893
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paul Clapham wrote:You don't even need the method reference:


Or even shorter:
If the Comparator argument is null it will use natural ordering (which is the same as using Comparator.naturalOrder()).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!