比较数组并删除重复项

时间:2019-01-08 17:30:11

标签: java arraylist

我想比较2个维数不同的数组,然后消除重复数组并将结果放在名为tmp的数组上

这是代码

ArrayList<String> list = new ArrayList<String>();
HashSet<String> tmp = new HashSet<String>();

try 
{
    String query1="SELECT ID FROM Apps;";
        ResultSet rs = con.createStatement().executeQuery(query1);
        while(rs.next())
        {
            list.add(rs.getString("ID"));
            tmp.add(rs.getString("ID"));
        }

        for(int i=0;i < check.size();i++)//ciclo  le checkbox selezionate
        {
                check.get(i);
                String query="UPDATE Apps SET Authorized='1' WHERE ID=" +check.get(i);//vado ad eseguire la query di update
                pr=con.prepareStatement(query);
                pr.executeUpdate();
                tmp.add(check.get(i).toString());
        }

        System.out.println(tmp);

两个数组的内容是:

check -> [1, 2]
list -> [1, 2, 3, 4, 5]

我想要的结果是tmp -> [3,4,5]

但控制台显示tmp -> [1,2,3,4,5]

3 个答案:

答案 0 :(得分:2)

您可以将所有内容添加到mktime()

hashSet

输出

    HashSet<String> h = new HashSet<String>(); 

    // Adding elements into HashSet usind add() 
    h.add("Cats");
    h.add("Cats"):
    h.add("Dogs"); 

    System.out.println("List:" + h); 

哈希集不会存储任何重复项。

答案 1 :(得分:2)

您可以这样删除重复项:

    public static void main(String[] args) {

    Set<Integer> tmp = new HashSet<>();
    List<Integer> check = new ArrayList<>();
    check.add(1);
    check.add(2);
    List<Integer> list = new ArrayList<>();
    for(int i = 1; i <= 5; i++){
        list.add(i);
    }

    tmp.addAll(list);
    tmp.removeAll(check);
    System.out.println(tmp);
}

答案 2 :(得分:-1)

尝试一下

public static void main(String[] args)
  {
    List<String> one = new ArrayList<>();
    one.add("one");
    one.add("two");
    one.add("three");
    one.add("in one");
    one.add("in two");

    List<String> two = new ArrayList<>();
    two.add("zero");
    two.add("one");
    two.add("two");
    two.add("four");
    two.add("not in one");
    two.add("in one");
    two.add("in two");

    // Depending on your needs create new or modify existing like one.addAll(two) and stream() from that.
    List<String> unique = one;
    unique.addAll(two);
    unique = unique.stream().distinct().collect(Collectors.toList());

    System.out.println("Unique list: " + unique.stream().collect(Collectors.joining(",")));
    // Unique list: one,two,three,in one,in two,zero,four,not in one
  }