use*_*786 13 java arrays string
这主要是一个表现问题.我有一个String数组AllUids中存在的所有用户的主列表.我还有一个String数组EndUids中存在的所有最终用户的列表.
我在Java工作,我的目标是从主列表AllUids中删除最终日期数组中存在的任何用户.我知道PHP有一个名为array_diff的函数.
我很好奇Java是否有任何可以比较两个数组并删除两者相似的元素.我的目标是这里的表现,这就是我询问内置功能的原因.我不想添加任何特殊包.
我想过写一个递归函数,但看起来效率很低.两个列表中都有数千个用户.要存在于结束日期列表中,您必须存在于AllUids列表中,直到被删除.
例:
String[] AllUids = {"Joe", "Tom", "Dan", "Bill", "Hector", "Ron"};
String[] EndUids = {"Dan", "Hector", "Ron"};
Run Code Online (Sandbox Code Playgroud)
我正在寻找的功能:
String[] ActiveUids = AllUids.RemoveSimilar(EndUids);
Run Code Online (Sandbox Code Playgroud)
ActiveUids看起来像这样:
{"Joe", "Tom", "Bill"}
Run Code Online (Sandbox Code Playgroud)
谢谢大家,显然我可以提出循环等但我不相信它会有效率.这是每天在生产机器上运行的东西.
Jon*_*Jon 13
Commons Collections有一个名为CollectionUtils的类和一个名为removeAll的静态方法,它接受一个初始列表和一个要从该列表中删除的东西列表:
Collection removeAll(Collection collection,
Collection remove)
Run Code Online (Sandbox Code Playgroud)
如果你使用用户列表而不是数组,那应该做你想要的.您可以使用Arrays.asList()将数组转换为一个列表,以便...
Collection ActiveUids = CollectionUtils.removeAll(Arrays.asList(AllUids),
Arrays.asList(EndUids))
Run Code Online (Sandbox Code Playgroud)
编辑:我也对Commons Collections进行了一些挖掘,并在Commons Collections中找到了ListUtils的以下解决方案:
List diff = ListUtils.subtract(Arrays.asList(AllUids), Arrays.asList(EndUids));
Run Code Online (Sandbox Code Playgroud)
很简约...
您无法从数组中"删除"元素.您可以将它们设置为null,但数组的大小是固定的.
您可以使用java.util.Set和removeAll从一个集合中取一个集合,但我更喜欢使用Google集合库:
Set<String> allUids = Sets.newHashSet("Joe", "Tom", "Dan",
"Bill", "Hector", "Ron");
Set<String> endUids = Sets.newHashSet("Dan", "Hector", "Ron");
Set<String> activeUids = Sets.difference(allUids, endUids);
Run Code Online (Sandbox Code Playgroud)
这有一个更实用的感觉.
小智 5
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Bireswhar
*/
import java.util.Collection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Repeated {
public static void main(String[] args) {
// Collection listOne = new ArrayList(Arrays.asList("milan","dingo", "elpha", "hafil", "meat", "iga", "neeta.peeta"));
// Collection listTwo = new ArrayList(Arrays.asList("hafil", "iga", "binga", "mike", "dingo"));
//
// listOne.retainAll( listTwo );
// System.out.println( listOne );
String[] s1 = {"ram", "raju", "seetha"};
String[] s2 = {"ram"};
List<String> s1List = new ArrayList(Arrays.asList(s1));
for (String s : s2) {
if (s1List.contains(s)) {
s1List.remove(s);
} else {
s1List.add(s);
}
System.out.println("intersect on " + s1List);
}
}
}
Run Code Online (Sandbox Code Playgroud)