0

I want to remove item that has a copy in the ArrayList list.

for example:

List = { 54,55,55 } NewList = {54}

OR

List = { 54,55,55,55 } NewList = {54,55}

MY CODE:

public void submit(){
        checked.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                int j = 0;
                int k = 1;
                int l =0;
                int size = list.size();
                String temp = "";

                //removing common
                while (j < size) {
                    while(k < size){
                        if(list.get(j) == list.get(k)){
                            list.remove(k);
                        }
                        k++;
                    }
                    j++;
                }

                int newsize = list.size();

                //printing
                while (l < newsize){
                    temp = temp + " " + list.get(l);
                    l++;

                }

                MessageTo.message(ViewTasksActivity.this, temp);

            }
        });

    }

My code only works on this condition for example:

list = {54,56,57,54}

and then clicked submit to clear off the list

list = {56,57} CORRECT

but with this conditions

list = {54,55,57,58,55}

and then clicked submit to clear off the list

list = {54,55,57,58,55} INCORRECT should remove 55

OR

list = {54,55,55,58,55}

and then clicked submit to clear off the list

list = {54,55,55,58,55} INCORRECT should remove 55 but remains only one 55 , should be {54,55,58}

-------Updates-------

FULL CODE

public class ViewTasksActivity extends AppCompatActivity {

    private GridLayout gridLayout;
    private Button b,checked;
    private CheckBox cb;

    ArrayList<Integer> list;

    public int goal_id,actid;
    int rowIndex = 1;
    int colIndex = 0;
    int rowIndex2 = 1;
    int colIndex2 = 1;
    int rowIndex3 = 1;
    int colIndex3 = 2;


    int i=0;



    MyDBAdapter dbhandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_tasks);

        Bundle extras = getIntent().getExtras();

        if (extras == null) {
            return;
        }

        //layout variables
        gridLayout = (GridLayout) findViewById(R.id.taskListLayout);
        checked = (Button)  findViewById(R.id.checktasks);

        goal_id = Integer.parseInt(extras.getString("goalid"));
        actid = Integer.parseInt(extras.getString("activityId"));

        list = new ArrayList<Integer>();

        dbhandler = new MyDBAdapter(this);

        set = new HashSet<>();

        displayAllTasks();
        submit();
    }

    public void displayAllTasks(){
        //get a list of all tasks
        List<Tasks> allTasks = dbhandler.getAllTasksbyActivity(goal_id,actid);

        for (final Tasks task : allTasks){

            //task name
            TextView textView2 = new TextView(ViewTasksActivity.this);
            GridLayout.LayoutParams param3 = new GridLayout.LayoutParams();
            param3.rowSpec = GridLayout.spec(rowIndex);
            param3.columnSpec = GridLayout.spec(colIndex);
            textView2.setTextColor(Color.BLACK);
            textView2.setLayoutParams(param3);
            textView2.setText(task.getTaskName());

            //status
            TextView textView = new TextView(ViewTasksActivity.this);
            GridLayout.LayoutParams param = new GridLayout.LayoutParams();
            param.rowSpec = GridLayout.spec(rowIndex2);
            param.columnSpec = GridLayout.spec(colIndex2);
            textView.setTextColor(Color.BLACK);
            textView.setLayoutParams(param);

            if(task.getComplete().equalsIgnoreCase("False")){
                cb = new CheckBox(ViewTasksActivity.this);
                GridLayout.LayoutParams param4 = new GridLayout.LayoutParams();
                param4.rowSpec = GridLayout.spec(rowIndex3);
                param4.columnSpec = GridLayout.spec(colIndex3);
                param4.setMargins(30, 5, 5, 5);
                cb.setLayoutParams(param4);
                cb.setId(task.getTaskId());
                cb.setClickable(Boolean.TRUE);

                textView.setText("   Incomplete");

                cb.setOnClickListener(new View.OnClickListener() {

                    public void onClick(View v) {
                            list.add(task.getTaskId());
                            i++;

                    }

                });

            }
            else
            {
                cb = new CheckBox(ViewTasksActivity.this);
                GridLayout.LayoutParams param5 = new GridLayout.LayoutParams();
                param5.rowSpec = GridLayout.spec(rowIndex3);
                param5.columnSpec = GridLayout.spec(colIndex3);
                param5.setMargins(30, 5, 5, 5);
                cb.setLayoutParams(param5);
                textView.setText("   Complete");
                cb.setId(task.getTaskId());
                cb.isChecked();
                cb.setClickable(Boolean.FALSE);




            }

            gridLayout.addView(textView);
            gridLayout.addView(textView2);
            gridLayout.addView(cb);
            rowIndex3++;
            rowIndex2++;
            rowIndex++;
        }


    }

    public void submit(){
        checked.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                int j = 0;
                    int k = 1;
                    int l =0;
                    int size = list.size();
                    String temp = "";

                    //removing common
                    while (j < size) {
                        while(k < size){
                            if(list.get(j) == list.get(k)){
                                list.remove(k);
                            }
                            k++;
                        }
                        j++;
                    }

                    int newsize = list.size();

                    //printing
                    while (l < newsize){
                        temp = temp + " " + list.get(l);
                        l++;

                    }

                    MessageTo.message(ViewTasksActivity.this, temp);

            }
        });

    }



    public void goBack(){
        Intent myIntent = new Intent(ViewTasksActivity.this, ViewActActivity.class);
        myIntent.putExtra("goalid", Integer.toString(goal_id));
        startActivity(myIntent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_view_tasks, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_back) {
            goBack();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
Lil Sis
  • 3
  • 3

5 Answers5

0

You're not resetting the index 'k' after each loop. So at the moment it's only checking the first element against all the others... You need to add:

    while (j < size) {
        // Add k = 0; here
        k = 0;
        while(k < size)
flinthart
  • 534
  • 1
  • 4
  • 14
0

If you want to remove pairs of identical values, so that [1, 1, 2] becomes [2], but [1, 1, 1, 2] becomes [1, 2], you can use a Set like this:

// list contains [1, 2, 3, 4, 2, 3, 2]

Set<Integer> set = new HashSet<>();

for (Integer i : list) {
    if (set.contains(i)) {
        set.remove(i);
    } else {
        set.add(i);
    }
}

list.clear();
list.addAll(set);
System.out.println(list); // [1, 2, 4]

If you want to preserve order, use LinkedHashSet instead.

Cinnam
  • 1,892
  • 1
  • 15
  • 23
  • Cant i convert the set back to ArrayList? – Lil Sis Oct 14 '15 at 17:29
  • How to convert the set back to ArrayList? – Lil Sis Oct 14 '15 at 17:30
  • @LilSis `list = new ArrayList(set);` – Cinnam Oct 14 '15 at 17:34
  • the problem i posted here is for this -> http://stackoverflow.com/questions/33127244/how-to-get-checkboxes-result-in-android ,, i tried to get all the checked checkboxes ids in the Arraylist. thats why i need no duplicates. and by pair removal. – Lil Sis Oct 14 '15 at 17:46
  • @LilSis Does your original code work, apart from not removing the duplicates correctly? If it does, then you should be able to just replace the removing algorithm with the one from my answer. Of course don't declare `list` as a local variable, that was just as an example. Also instead of creating a new list in the end, you can do `list.clear(); list.addAll(set);`. – Cinnam Oct 14 '15 at 17:57
  • THANKS. IT WORK NOW :D :D – Lil Sis Oct 14 '15 at 18:15
0
public ArrayList<int> cleanList(ArrayList<int> list){
  ArrayList<int> newList = new ArrayList<int>();
  for(int i = 0; i < list.size(); i++){
    int item = list.get(i);
    if(!newList.contains(item)){
      newList.add(item);
    }
  }
  return newList;
}

A few answers below recommend using Set which I agree with but in case you need to use an ArrayList for some reason heres a clean clear way of doing it. Only one loop through the list and you return a new ArrayList thats been cleaned up.

Shrey
  • 671
  • 7
  • 14
0

You can remove the items by again looping in through the arrayList. But again it increases the time complexity.

Why not use Sets instead, the duplicate elements will be prohibited.

Set<Integer> set = new HashSet<Integer>();
set.add();
Ritt
  • 3,181
  • 3
  • 22
  • 51
0

At the below there is an alternative way to remove duplicate values. I added comments on my code.

public static void main(String[] args) {

    ArrayList<Integer> myList = new ArrayList<Integer>();

    myList.addAll(Arrays.asList(new Integer[] { 33, 34, 34, 33 }));

    System.out.println(removeDuplicateValues(myList));
}

public static ArrayList<Integer> removeDuplicateValues(ArrayList<Integer> list) {
    Integer[] myList = new Integer[list.size()];
    myList = list.toArray(myList); // we should copy our array at the first because we will modify the original one in the loop.
    for (Integer integer : myList) {
        list.remove(integer); // first remove the integer
        if (!list.contains(integer))
            list.add(integer); // add it again if it does not exist afer removing.
    }
    return list;
}

prints: [33, 34] while our arraylist has the values: [33, 34, 34, 33]

if you want to remove all duplicate values:

public static void main(String[] args) {
    ArrayList<Integer> myList = new ArrayList<Integer>();
    myList.addAll(Arrays.asList(new Integer[] { 35, 34, 34, 33 }));
    System.out.println(removeAllDublicateValues(myList));
}

public static ArrayList<Integer> removeAllDuplicateValues(ArrayList<Integer> list) {
    Integer[] myList = new Integer[list.size()];
    myList = list.toArray(myList); // we should copy our array at the first because we will modify the original one in the loop.

    List<Integer> duplicateList = new ArrayList<Integer>();

    for (Integer integer : myList) {
        list.remove(integer); // first remove the integer
        if (!list.contains(integer) && !duplicateList.contains(integer))
            list.add(integer); // add it again if it does not exist afer removing. And it is not a diplicate value
        else 
            duplicateList.add(integer);

    }
    return list;
}

prints: [35, 33] while our arraylist has the values: [35, 34, 34, 33]

Sedat Polat
  • 1,631
  • 2
  • 18
  • 28