sort(comparator) removes duplicates. There is no extra parameter to preserve duplicates.
A simple solution would be to use efficient sorting algorithms like Merge Sort, Quicksort, Heapsort, etc., that can solve this problem in O(n. log(n)) time, but those will not take advantage of the fact that there are many duplicated values in the array. A better approach is to use a counting sort.
Use the Python List sort() method to sort a list in place. The sort() method sorts the string elements in alphabetical order and sorts the numeric elements from smallest to largest. Use the sort(reverse=True) to reverse the default sort order.
You can use Collections
for to sort data:
import java.util.Collections;
import java.util.ArrayList;
import java.util.List;
public class tes
{
public static void main(String args[])
{
List<Integer> lList = new ArrayList<Integer>();
lList.add(4);
lList.add(1);
lList.add(7);
lList.add(2);
lList.add(9);
lList.add(1);
lList.add(5);
Collections.sort(lList);
for(int i=0; i<lList.size();i++ )
{
System.out.println(lList.get(i));
}
}
}
Ascending order:
Collections.sort(lList);
Descending order:
Collections.sort(lList, Collections.reverseOrder());
Use Collections class API to sort.
Collections.sort(list);
Just use Collections.sort(yourListHere)
here to sort.
You can read more about Collections from here.
To sort in ascending order :
Collections.sort(lList);
And for reverse order :
Collections.reverse(lList);
You are using Lists, concrete ArrayList. ArrayList also implements Collection interface. Collection interface has sort method which is used to sort the elements present in the specified list of Collection in ascending order. This will be the quickest and possibly the best way for your case.
Sorting a list in ascending order can be performed as default operation on this way:
Collections.sort(list);
Sorting a list in descending order can be performed on this way:
Collections.reverse(list);
According to these facts, your solution has to be written like this:
public class tes
{
public static void main(String args[])
{
List<Integer> lList = new ArrayList<Integer>();
lList.add(4);
lList.add(1);
lList.add(7);
lList.add(2);
lList.add(9);
lList.add(1);
lList.add(5);
Collections.sort(lList);
for(int i=0; i<lList.size();i++ )
{
System.out.println(lList.get(i));
}
}
}
More about Collections you can read here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With