LinkedList is doubly-linked list implementation of the List and Deque interfaces.
How to sort elements of Java LinkedList?
We can use Java LinkedList sort method for sorting it's elements. Below is the program of LinkedList sort example. You can see in details about sort method in Comparable and Comparator post.
package com.walking.techie; import java.util.LinkedList; import java.util.Comparator; import java.util.List; public class LinkedListSortingDemo { public static void main(String[] args) { List<Integer> numbers = new LinkedList<Integer>(); numbers.add(23); numbers.add(34); numbers.add(13); numbers.add(2); numbers.add(28); System.out.println("Original numbers list before sorting " + numbers); MyComparator<Integer> comp = new LinkedListSortingDemo().new MyComparator<Integer>(); numbers.sort(comp); System.out.println("numbers list after sorting " + numbers); } class MyComparator<T> implements Comparator<Integer> { @Override public int compare(Integer o1, Integer o2) { return (o1 - o2); } } }
Output of above program is shown below:
Original numbers list before sorting [23, 34, 13, 2, 28] numbers list after sorting [2, 13, 23, 28, 34]
No comments :
Post a Comment