In: Computer Science
how to use java ArrayList to get the result?
removing consecutive duplicates
eg [1 2 2 3 2 2 1] ------->[1 2 3 2 1]
Solution Description:
Add elements to input_Array list and then call a function which accepts the array list and returns the array list.
Inside the function declare a temp array list and add the first element of input.
after that run the loop from 0 to size of input_list and check if the current and previous elements are matched or not.if not then add it to temp list.
At last returns the temp Array List .
Code:
import java.util.*;
public class RemoveConsecutiveDuplicates
{
public static ArrayList<Integer>
removeConsecutiveDups(ArrayList<Integer> input_list)
//function removeConsecutiveDups() which accepts ArrayList and
retunrs it
{
ArrayList<Integer> temp = new ArrayList<Integer>();
//initalize new temp ArrayList
temp.add(input_list.get(0)); //add the starting value of input_list
to temp
for(int i = 1; i < input_list.size(); i++) //iterate the loop
from 0 to size of ArrayList
{
if(input_list.get(i-1) != input_list.get(i)) //check if the present
and previous elements are same if not
{
temp.add(input_list.get(i)); //add to temp list
}
}
return temp; //finally returns the ArrayList
}
public static void main(String args[])
{
ArrayList<Integer> input_list = new
ArrayList<Integer>(); //Array List Declaration
input_list.add(1);
input_list.add(2);
input_list.add(3); //add input numbers to input_list
input_list.add(2);
input_list.add(2);
input_list.add(1);
ArrayList<Integer> newList =
removeConsecutiveDups(input_list); //call removeConsecutiveDups()
functon with passing input_list and store the result
System.out.println("Final List after removing all consecutive
duplicates: " + newList); //finally print the result
}
}
Code and Output Screenshots:
Note : if you have any queries please post a comment thanks a lot...always available to help you...