Monday, January 20, 2025
HomeProgrammingHow can I sort an Array List in Java?

How can I sort an Array List in Java?

How can I sort an Array List in Java?

To sort an Array List in Java, you can use the Collections. Sort method, which sorts the elements based on their natural ordering (for comparable types) or a custom comparator (for other types).

See also  How do I make a transparent canvas in html5?

Example: import java.util.Array List;
import java.util.Collections;

public class Main (public static void main String args)
Array List<String> list = new ArrayList<>
list.add (“Orange”)
list.add (“Apple”)
list.add (“Banana”)

Collections.sort (list)

System.out.println (list)

This will sort the Array List in ascending order. If you want to sort it in descending order, you can use the Collections. Sort method with a custom comparator:

See also  "How do you import packages in Python?"

Collections. Sort (list, Collections. reverse Order

Alternatively, you can use the List. Sort method (available in Java 8 and later) to sort the Array List

 

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x