【问题标题】:How to remove Common items in ArrayList Android如何删除 ArrayList Android 中的常用项
【发布时间】:2015-10-15 02:36:08
【问题描述】:

我想删除在 ArrayList 列表中有副本的项目。

例如:

列表 = { 54,55,55 } 新列表 = {54}

或

列表 = { 54,55,55,55 } 新列表 = {54,55}

我的代码:

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);

            }
        });

    }

我的代码仅适用于这种情况,例如:

列表 = {54,56,57,54}

然后点击提交清除列表

list = {56,57} 正确

但在这个条件下

列表 = {54,55,57,58,55}

然后点击提交清除列表

list = {54,55,57,58,55} INCORRECT 应该删除 55

或

列表 = {54,55,55,58,55}

然后点击提交清除列表

list = {54,55,55,58,55} INCORRECT 应该删除 55 但只保留一个 55 ,应该是 {54,55,58}

-------更新-------

完整代码

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);
    }
}

【问题讨论】:

  • 使用 Set 而不是 List。
  • 设置只会删除重复的。我想删除该项目及其重复项。
  • 你从来没有在你的内部循环中重置k,应该在进入while()之前将它设置为0,你也不要在删除元素后将大小设置为新值
  • 所以你想删除pairs,对吗? [1, 1, 1, 1, 2]应该变成[2],[1, 1, 1, 1, 1, 2]应该变成[1, 2],对吗?

标签: java android arraylist


【解决方案1】:

如果你想删除对相同的值,让[1, 1, 2]变成[2],但[1, 1, 1, 2]变成[1, 2],你可以像这样使用Set:

// 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]

如果您想保持秩序,请改用LinkedHashSet。

【讨论】:

  • 我不能将集合转换回 ArrayList 吗?
  • 如何将集合转回ArrayList?
  • @LilSis list = new ArrayList&lt;Integer&gt;(set);
  • 我在这里发布的问题是针对这个 -> stackoverflow.com/questions/33127244/…,我试图在 Arraylist 中获取所有选中的复选框 id。这就是为什么我不需要重复。并通过对删除。
  • @LilSis 除了没有正确删除重复项之外,您的原始代码是否有效?如果是这样,那么您应该能够将删除算法替换为我的答案中的算法。当然不要将list 声明为局部变量,这只是一个示例。最后,您可以使用list.clear(); list.addAll(set);,而不是创建一个新列表。
【解决方案2】:

您不会在每次循环后重置索引“k”。 所以目前它只检查第一个元素与所有其他元素...... 您需要添加:

    while (j < size) {
        // Add k = 0; here
        k = 0;
        while(k < size)

【讨论】:

    【解决方案3】:
    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;
    }
    

    下面的一些答案建议使用我同意的Set,但如果您出于某种原因需要使用ArrayList,这是一种清晰明了的方法。只有一个循环遍历列表,然后您返回一个已清理的新 ArrayList。

    【讨论】:

      【解决方案4】:

      您可以通过再次循环进入 arrayList 来删除项目。但这又增加了时间复杂度。

      为什么不改用Sets,重复的元素会被禁止。

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

      【讨论】:

      • 只删除重复项
      【解决方案5】:

      在下面,有另一种删除重复值的方法。我在代码中添加了 cmets。

      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] 而我们的 arraylist 的值是:[33, 34, 34, 33]

      如果要删除所有重复值:

      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] 而我们的 arraylist 的值是:[35, 34, 34, 33]

      【讨论】:

      • 它返回一个新的ArrayList?
      • @LilSis 您需要哪种类型的列表?
      • 当我使用该代码单击提交功能时,应用程序无响应
      • 我的错,我忘记了什么。 XD
      • 我也想删除带有重复项的项目,而不仅仅是重复项。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-14
      • 2017-12-21
      • 1970-01-01
      相关资源
      最近更新 更多