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).

Alessandro Messori
  • 1,035
  • 1
  • 14
  • 23
  • Maybe if you use the [stream API](https://stackoverflow.com/questions/40517977/sorting-a-list-with-stream-sorted-in-java) you can do it that way. – ernest_k Dec 01 '20 at 10:47
  • 1
    https://stackoverflow.com/questions/40517977/sorting-a-list-with-stream-sorted-in-java – jr593 Dec 01 '20 at 10:48
  • Java 8 streams is what you are after: https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html – stridecolossus Dec 01 '20 at 10:49
  • thanks to everyone who answered,the stream API seems to be what I'm looking for – Alessandro Messori Dec 01 '20 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. – Ralf Kleberhoff Dec 01 '20 at 12:06

1 Answers1

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);
Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36