0

I am learning Java and while trying to sort an ArrayList of objects I found this way of doing it.

ArrayList<String> al = new ArrayList<String>(); al.add("Friends"); al.add("Dear"); al.add("Is"); al.add("Superb"); Collections.sort(al); System.out.println("List after the use of" + " Collection.sort() :\n" + al); 

This method works but since I come from a functional programming background I was wondering what are the most elegant ways to do sorting on a collection in Java in functional style (so by returning a new collection and not by modifying the original one).

5
  • Maybe if you use the stream API you can do it that way. Commented Dec 1, 2020 at 10:47
  • 1
    stackoverflow.com/questions/40517977/… Commented Dec 1, 2020 at 10:48
  • Java 8 streams is what you are after: docs.oracle.com/javase/8/docs/api/java/util/stream/… Commented Dec 1, 2020 at 10:49
  • thanks to everyone who answered,the stream API seems to be what I'm looking for Commented Dec 1, 2020 at 10:56
  • Why not wrap copying the list plus sorting the copy into your own method? If the language/framework you're using doesn't quite match the language you want to use for expressing your program, create the missing parts. Commented Dec 1, 2020 at 12:06

1 Answer 1

0

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:

List result = al.stream().sorted((o1, o2) -> o1.compareTo(o2)).collect(Collectors.toList()); 

or :

ArrayList<String> al = new ArrayList<String>(); al.add("Friends"); al.add("Dear"); al.add("Is"); al.add("Superb"); System.out.println(al); al.sort((o1, o2) -> o1.compareTo(o2)); System.out.println(al); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.