In: Computer Science
CS 209 Data Structure
1. Create a method that takes an ArrayList of Integer and returns a sorted copy of that ArrayList with no duplicates.
Sample Input: {5, 7, 4, 6, 5, 6, 9, 7}
Sample Output: {4, 5, 6, 7, 9}
Implementation in JAVA;
I have tried to explain through several methods:
or I implemented sorting and removing duplicates from ArrayList through Several Methods
just have a look on whole code:
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class Remove_Duplicate_and_sort_list {
// will sort elements in list by using Bubble
sort
public static ArrayList<Integer>
sort(ArrayList<Integer> list){
for (int i = 0; i < list.size();
i++) {
for (int j = list.size() - 1; j
> i; j--) {
if (list.get(i) > list.get(j))
{
int tmp = list.get(i);
list.set(i,list.get(j));
list.set(j,tmp);
}
}
}
return list;
}
// this is easiest method to sort a list by using
collections
public static ArrayList<Integer>
sort_directlt(ArrayList<Integer> list){
Collections.sort(list);
return list;
}
// this method is valid for remove duplicates from
sorted lists only
public static ArrayList<Integer>
removeduplicates(ArrayList<Integer> list){
for(int i=1;i<list.size();i++) {
if(list.get(i)==list.get(i-1)) {
list.remove(i-1);
}
}
return list;
}
// very easiest method to remove duplicates from
arrayList by using Set
public static ArrayList<Integer>
removeduplicates_directly(ArrayList<Integer> list){
Set<Integer> hashsetList =
new HashSet<Integer>(list);
return (ArrayList<Integer>)
hashsetList;
}
// one another method for removing duplicates and will
valid for sorted and unsorted all lists
public static ArrayList<Integer>
removeduplicates_method2(ArrayList<Integer> al){
for(int
i=0;i<al.size();i++){
for(int
j=i+1;j<al.size();j++){
if(al.get(i).equals(al.get(j))){
al.remove(j);
j--;
}
}
}
return al;
}
// driver method and main method
public static void main(String[] args) {
ArrayList<Integer> list = new
ArrayList<Integer> ();
list.add(5);
list.add(7);
list.add(4);
list.add(6);
list.add(5);
list.add(6);
list.add(9);
list.add(7);
System.out.println("The input list is : "+list);
list=sort(list);
list=removeduplicates(list);
System.out.println("After sorting and remove
Duplicates list is : "+list);
}
}
SAMPLE OUTPUT:
If you have any doubt regarding this question please ask me in comments
// THANK YOU:-)