如何获取String [] A - String [] B,即所有在A中但不在B中的元素,在java中?

时间:2014-12-04 05:31:05

标签: java arrays

我有一个String [] allEmps;所有emps的字符串数组;

String [] allEmps = StringUtil.convertCommaStringToArray(listOfEmpsCommaSep, ",");

我有另一个String [] EmpsWithCompensationDefined

String [] listOfEmpsWithCompDefined =  DBUtility.selectFieldAndReturnAsStringArray(QueryToGetEmpsWhomCompIsDefined, con);

现在我想让没有定义赔偿的雇员,即A中但不在B中的条目。

解决方案:我可以迭代两个数组并获得差异。但这将是O(n ^ 2)复杂。还有其他方法可以减少渐近复杂度吗?

编辑:

ArrayList listOfFilteredEmps = new ArrayList();
                    for(int j =0;j<allEmps.length;j++){
                        boolean isMatched = false;
                        for(int i=0;i<listOfEmpsWithCompDefined.length;i++){
                            if(allEmps[j]==listOfEmpsWithCompDefined[i]){
                                isMatched = true;
                            }
                        }
                        if(!isMatched){
                            if(listOfFilteredEmps!=null && listOfFilteredEmps.size()==0){
                                listOfFilteredEmps.add(allEmps[j]);
                            }else{
                                listOfFilteredEmps.add(","+allEmps[j]);
                            }
                        }
                    }

1 个答案:

答案 0 :(得分:5)

你可以这样试试

String [] allEmps={"A","B","C","D"};
String [] listOfEmpsWithCompDefined={"A","D","E"};
Set<String> mySet1 = new HashSet<>(Arrays.asList(allEmps)); // convert to set
Set<String> mySet2 = new HashSet<>(Arrays.asList(listOfEmpsWithCompDefined));
mySet1.removeAll(mySet2);// elements which are in A but not in B 
String[] df = mySet1.toArray(new String[mySet1.size()]);// difference