Java中ArrayList的交并
有没有办法做到这一点?我在找,但找不到 另一个问题:我需要这些方法,以便可以过滤文件。 有些是Java中ArrayList的交并,java,list,union,intersection,Java,List,Union,Intersection,有没有办法做到这一点?我在找,但找不到 另一个问题:我需要这些方法,以便可以过滤文件。 有些是和过滤器,有些是或过滤器(如在集合论中),因此我需要根据所有文件和保存这些文件的联合/相交数组列表进行过滤 我应该使用不同的数据结构来保存文件吗?还有什么可以提供更好的运行时吗?您可以从中使用CollectionUtils 将removeAll,然后addAll 在集合文档中查找更多信息(ArrayList是一个集合) (因此ArrayList还具有: 如果接受重复,则使用列表实现;如果不接受,则使用集
和
过滤器,有些是或
过滤器(如在集合论中),因此我需要根据所有文件和保存这些文件的联合/相交数组列表进行过滤
我应该使用不同的数据结构来保存文件吗?还有什么可以提供更好的运行时吗?您可以从中使用
CollectionUtils
将removeAll
,然后addAll
在集合文档中查找更多信息(ArrayList是一个集合)
(因此ArrayList还具有:
如果接受重复,则使用列表实现;如果不接受,则使用集合实现:
Collection<String> col1 = new ArrayList<String>(); // {a, b, c}
// Collection<String> col1 = new TreeSet<String>();
col1.add("a");
col1.add("b");
col1.add("c");
Collection<String> col2 = new ArrayList<String>(); // {b, c, d, e}
// Collection<String> col2 = new TreeSet<String>();
col2.add("b");
col2.add("c");
col2.add("d");
col2.add("e");
col1.addAll(col2);
System.out.println(col1);
//output for ArrayList: [a, b, c, b, c, d, e]
//output for TreeSet: [a, b, c, d, e]
col1集合=新的ArrayList();//{a,b,c}
//集合col1=新树集();
第1栏添加(“a”);
第1栏:添加(“b”);
第1栏添加(“c”);
集合col2=新的ArrayList();//{b,c,d,e}
//集合col2=新树集();
col2.添加(“b”);
col2.添加(“c”);
col2.添加(“d”);
col2.添加(“e”);
col1.addAll(col2);
System.out.println(col1);
//ArrayList的输出:[a,b,c,b,c,d,e]
//树集的输出:[a、b、c、d、e]
如果你有一组数据,你可以使用Guava的类。我认为如果你想对文件进行交集和并集,你应该使用一个集合来保存文件。然后,您可以使用的类执行并集
,交集
以及通过谓词进行过滤。这些方法与其他建议的不同之处在于,所有这些方法都会创建两个集合的并集、交集等的惰性视图。Apache Commons创建一个新集合并将数据复制到其中retainAll
通过删除集合中的元素来更改其中一个集合。仅为集合而不是列表定义的并集和交集。正如你提到的
检查库中的筛选器。番石榴还提供真正的
static Set.SetViewunion(Set set2)
这是一个不使用任何第三方库的简单实现。与retainal
、removeAll
和addAll
相比,这些方法的主要优点是不修改输入到方法中的原始列表
public class Test {
public static void main(String... args) throws Exception {
List<String> list1 = new ArrayList<String>(Arrays.asList("A", "B", "C"));
List<String> list2 = new ArrayList<String>(Arrays.asList("B", "C", "D", "E", "F"));
System.out.println(new Test().intersection(list1, list2));
System.out.println(new Test().union(list1, list2));
}
public <T> List<T> union(List<T> list1, List<T> list2) {
Set<T> set = new HashSet<T>();
set.addAll(list1);
set.addAll(list2);
return new ArrayList<T>(set);
}
public <T> List<T> intersection(List<T> list1, List<T> list2) {
List<T> list = new ArrayList<T>();
for (T t : list1) {
if(list2.contains(t)) {
list.add(t);
}
}
return list;
}
}
公共类测试{
公共静态void main(字符串…参数)引发异常{
List list1=新的ArrayList(Arrays.asList(“A”、“B”、“C”));
List list2=新的ArrayList(Arrays.asList(“B”、“C”、“D”、“E”、“F”));
System.out.println(newtest().intersection(list1,list2));
System.out.println(newtest().union(list1,list2));
}
公共列表联合(列表1、列表2){
Set=newhashset();
set.addAll(列表1);
set.addAll(列表2);
返回新的ArrayList(集合);
}
公共列表交叉点(列表1、列表2){
列表=新的ArrayList();
for(T:list1){
if(列表2.contains(t)){
列表。添加(t);
}
}
退货清单;
}
}
标记的解决方案无效。它的时间复杂度为O(n^2)。我们可以做的是对两个列表进行排序,然后执行一个交集算法,如下所示
private static ArrayList<Integer> interesect(ArrayList<Integer> f, ArrayList<Integer> s) {
ArrayList<Integer> res = new ArrayList<Integer>();
int i = 0, j = 0;
while (i != f.size() && j != s.size()) {
if (f.get(i) < s.get(j)) {
i ++;
} else if (f.get(i) > s.get(j)) {
j ++;
} else {
res.add(f.get(i));
i ++; j ++;
}
}
return res;
}
private static ArrayList interestect(ArrayList f,ArrayList s){
ArrayList res=新的ArrayList();
int i=0,j=0;
而(i!=f.size()&&j!=s.size()){
如果(f.get(i)s.get(j)){
j++;
}否则{
决议添加(f.get(i));
i++;j++;
}
}
返回res;
}
这个函数的复杂度是O(n logn+n),它位于O(n logn)中。
工会也是以类似的方式进行的。只需确保对if-elseif-else语句进行适当的修改
如果你想使用迭代器,我也可以使用(我知道它们在C++中更有效,我也不知道java中是否也是这样)。p> 下面是一种与流相交的方法(记住,流必须使用java 8):
listwoolist1=newarraylist(Arrays.asList(new foo(),new foo());
listwoolist2=newarraylist(Arrays.asList(newfoo(),newfoo());
foulist1.stream().filter(f->foulist2.contains(f)).collect(collector.toList());
不同类型列表的示例。如果您在foo和bar之间有关联,并且您可以从foo获得bar对象,那么您可以修改流:
List<foo> fooList = new ArrayList<>(Arrays.asList(new foo(), new foo()));
List<bar> barList = new ArrayList<>(Arrays.asList(new bar(), new bar()));
fooList.stream().filter(f -> barList.contains(f.getBar()).collect(Collectors.toList());
listwoolist=newarraylist(Arrays.asList(newfoo(),newfoo());
List barList=newarraylist(Arrays.asList(new bar(),new bar());
foulist.stream().filter(f->barList.contains(f.getBar()).collect(Collectors.toList());
- retainAll将修改您的列表
- Guava没有用于列表的API(仅用于集合)
我发现ListUtils对于这个用例非常有用
如果不想修改现有列表,请使用org.apache.commons.collections中的ListUtils
ListUtils.intersection(list1,list2)
这篇文章很老了,但它是谷歌搜索该主题时出现的第一篇文章
我想使用Java 8 streams在一行中做(基本上)相同的事情来进行更新:
List<T> intersect = list1.stream()
.filter(list2::contains)
.collect(Collectors.toList());
List<T> union = Stream.concat(list1.stream(), list2.stream())
.distinct()
.collect(Collectors.toList());
List intersect=list1.stream()
.filter(列表2::包含)
.collect(Collectors.toList());
List union=Stream.concat(list1.Stream(),list2.Stream())
.distinct()
.collect(Collectors.toList());
如果有人有更好/更快的解决方案,请告诉我,但此解决方案是一个很好的单行程序,可以轻松地包含在方法中,而无需添加不必要的帮助器类/方法,并且仍然保持可读性。如果列表中的对象是可散列的(即具有适当的散列代码和equals函数),表之间大约大小>20的最快方法是为两个列表中较大的一个构建哈希集
public static <T> ArrayList<T> intersection(Collection<T> a, Collection<T> b) {
if (b.size() > a.size()) {
return intersection(b, a);
} else {
if (b.size() > 20 && !(a instanceof HashSet)) {
a = new HashSet(a);
}
ArrayList<T> result = new ArrayList();
for (T objb : b) {
if (a.contains(objb)) {
result.add(objb);
}
}
return result;
}
}
publicstatica
List<foo> fooList1 = new ArrayList<>(Arrays.asList(new foo(), new foo()));
List<foo> fooList2 = new ArrayList<>(Arrays.asList(new foo(), new foo()));
fooList1.stream().filter(f -> fooList2.contains(f)).collect(Collectors.toList());
List<foo> fooList = new ArrayList<>(Arrays.asList(new foo(), new foo()));
List<bar> barList = new ArrayList<>(Arrays.asList(new bar(), new bar()));
fooList.stream().filter(f -> barList.contains(f.getBar()).collect(Collectors.toList());
List<T> intersect = list1.stream()
.filter(list2::contains)
.collect(Collectors.toList());
List<T> union = Stream.concat(list1.stream(), list2.stream())
.distinct()
.collect(Collectors.toList());
public static <T> ArrayList<T> intersection(Collection<T> a, Collection<T> b) {
if (b.size() > a.size()) {
return intersection(b, a);
} else {
if (b.size() > 20 && !(a instanceof HashSet)) {
a = new HashSet(a);
}
ArrayList<T> result = new ArrayList();
for (T objb : b) {
if (a.contains(objb)) {
result.add(objb);
}
}
return result;
}
}
//all sorted items from both
public <T> List<T> getListReunion(List<T> list1, List<T> list2) {
Set<T> set = new HashSet<T>();
set.addAll(list1);
set.addAll(list2);
return new ArrayList<T>(set);
}
//common items from both
public <T> List<T> getListIntersection(List<T> list1, List<T> list2) {
list1.retainAll(list2);
return list1;
}
//common items from list1 not present in list2
public <T> List<T> getListDifference(List<T> list1, List<T> list2) {
list1.removeAll(list2);
return list1;
}
ArrayList<String> AbsentDates = new ArrayList<String>();//This Array will store difference
public void AbsentDays() {
findDates("April", "2017");//Array one with dates in Month April 2017
findPresentDays();//Array two carrying some dates which are subset of Dates in Month April 2017
for (int i = 0; i < Dates.size(); i++) {
for (int j = 0; j < PresentDates.size(); j++) {
if (Dates.get(i).equals(PresentDates.get(j))) {
Dates.remove(i);
}
}
AbsentDates = Dates;
}
System.out.println(AbsentDates );
}
class Intersection
{
public static void main(String[] args)
{
String s="";
int[] array1 = {1, 2, 5, 5, 8, 9, 7,2,3512451,4,4,5 ,10};
int[] array2 = {1, 0, 6, 15, 6, 5,4, 1,7, 0,5,4,5,2,3,8,5,3512451};
for (int i = 0; i < array1.length; i++)
{
for (int j = 0; j < array2.length; j++)
{
char c=(char)(array1[i]);
if(array1[i] == (array2[j])&&s.indexOf(c)==-1)
{
System.out.println("Common element is : "+(array1[i]));
s+=c;
}
}
}
}
public class Union {
public static void main(String[] args){
int arr1[]={1,3,3,2,4,2,3,3,5,2,1,99};
int arr2[]={1,3,2,1,3,2,4,6,3,4};
int arr3[]=new int[arr1.length+arr2.length];
for(int i=0;i<arr1.length;i++)
arr3[i]=arr1[i];
for(int i=0;i<arr2.length;i++)
arr3[arr1.length+i]=arr2[i];
System.out.println(Arrays.toString(arr3));
for(int i=0;i<arr3.length;i++)
{
for(int j=i+1;j<arr3.length;j++)
{
if(arr3[i]==arr3[j])
arr3[j]=99999999; //line 12
}
}
for(int i=0;i<arr3.length;i++)
{
if(arr3[i]!=99999999)
System.out.print(arr3[i]+" ");
}
}
}
public static <T> Collection<T> getIntersection(Collection<T> coll1, Collection<T> coll2){
return Stream.concat(coll1.stream(), coll2.stream())
.filter(coll1::contains)
.filter(coll2::contains)
.collect(Collectors.toSet());
}
public static <T> Collection<T> getMinus(Collection<T> coll1, Collection<T> coll2){
return coll1.stream().filter(not(coll2::contains)).collect(Collectors.toSet());
}
public static <T> Predicate<T> not(Predicate<T> t) {
return t.negate();
}
Collection<Integer> collection1 = Arrays.asList(1, 2, 4, 5, 7, 8);
Collection<Integer> collection2 = Arrays.asList(2, 3, 4, 6, 8);
Collection<Integer> intersection = CollectionUtils.intersection(collection1, collection2);
System.out.println(intersection); // [2, 4, 8]
Collection<Integer> union = CollectionUtils.union(collection1, collection2);
System.out.println(union); // [1, 2, 3, 4, 5, 6, 7, 8]
Collection<Integer> subtract = CollectionUtils.subtract(collection1, collection2);
System.out.println(subtract); // [1, 5, 7]
public static List<String> hashMapIntersection(List<String> target, List<String> support) {
List<String> r = new ArrayList<String>();
Map<String, Integer> map = new HashMap<String, Integer>();
for (String s : support) {
map.put(s, 0);
}
for (String s : target) {
if (map.containsKey(s)) {
r.add(s);
}
}
return r;
}
public static List<String> hashSetIntersection(List<String> a, List<String> b) {
Long start = System.currentTimeMillis();
List<String> r = new ArrayList<String>();
Set<String> set = new HashSet<String>(b);
for (String s : a) {
if (set.contains(s)) {
r.add(s);
}
}
print("intersection:" + r.size() + "-" + String.valueOf(System.currentTimeMillis() - start));
return r;
}
public static void union(List<String> a, List<String> b) {
Long start = System.currentTimeMillis();
Set<String> r= new HashSet<String>(a);
r.addAll(b);
print("union:" + r.size() + "-" + String.valueOf(System.currentTimeMillis() - start));
}
private List<User> intersection(List<User> users, List<OtherUser> list) {
return list.stream()
.flatMap(OtherUser -> users.stream()
.filter(user -> user.getId()
.equalsIgnoreCase(OtherUser.getId())))
.collect(Collectors.toList());
}
public static <T> Set<T> intersectCollections(Collection<T> col1, Collection<T> col2) {
Set<T> set1, set2;
if (col1 instanceof Set) {
set1 = (Set) col1;
} else {
set1 = new HashSet<>(col1);
}
if (col2 instanceof Set) {
set2 = (Set) col2;
} else {
set2 = new HashSet<>(col2);
}
Set<T> intersection = new HashSet<>(Math.min(set1.size(), set2.size()));
for (T t : set1) {
if (set2.contains(t)) {
intersection.add(t);
}
}
return intersection;
}
public static <T> Set<T> intersectCollections(Collection<T> col1, Collection<T> col2) {
boolean isCol1Larger = col1.size() > col2.size();
Set<T> largerSet;
Collection<T> smallerCol;
if (isCol1Larger) {
if (col1 instanceof Set) {
largerSet = (Set<T>) col1;
} else {
largerSet = new HashSet<>(col1);
}
smallerCol = col2;
} else {
if (col2 instanceof Set) {
largerSet = (Set<T>) col2;
} else {
largerSet = new HashSet<>(col2);
}
smallerCol = col1;
}
return smallerCol.stream()
.filter(largerSet::contains)
.collect(Collectors.toSet());
}
col1.stream().filter(col2::contains).collect(Collectors.toList());
return concat(a.stream(), b.stream()).collect(toList());
return concat(a.stream(), b.stream()).distinct().collect(toList());
return concat(a.stream(), b.stream()).collect(toSet());
return a.stream().filter(b::contains).collect(toList());
return a.stream().distinct().filter(b::contains).collect(toList());