gpt4 book ai didi

java - 克隆集合成员匹配条件

转载 作者:行者123 更新时间:2023-11-30 03:07:15 26 4
gpt4 key购买 nike

我正在尝试编写一个方法,当传递一个数组列表时,将返回一个新的数组列表,其中仅包含与指定条件匹配的成员(不使用迭代)。集合类有一个类似的removeIf,但我正在寻找一个“copyIf”(如果存在任何此类功能)。例如:

public class Foo {
public int value;
public Foo(int val){
value = val;
}
}

public class Bar {
private ArrayList<Foo> refList;
public ArrayList<Foo> overTwentyList;

public Bar(){
refList = new ArrayList<Foo>();
refList.add(new Foo(12));
refList.add(new Foo(23));
refList.add(new Foo(6));
refList.add(new Foo(44));
refList.add(new Foo(2));
refList.add(new Foo(19));
refList.add(new Foo(99));
refList.add(new Foo(74));

overTwentyList = overTwenty(refList);
// now overTwentyList would contain only Foo members
// with values 23, 44, 99, 74 and refList would retain
// all values
}

public ArrayList<Foo> overTwenty(ArrayList<Foo> bankList){
// bankList filter code here
// normally i would use iteration but i think
// calling this method frequently would eat a lot
// of system resources if it iterates every time
return filteredList;
}
}

最佳答案

肯定是over twenty列表只是列表的副本,将全部 under twenty条目已删除。您可以使用 removeIf 来做到这一点.

    public ArrayList<Foo> overTwenty(ArrayList<Foo> bankList) {
// Take a complete copy.
ArrayList<Foo> filtered = new ArrayList<>(bankList);
// Remove the under 20s.
filtered.removeIf(a -> a.value <= 20);
return filtered;
}

但是,这仍然每次都会复制整个列表。你需要更多的回旋余地来避免这种情况。会Iterable<Foo>可以接受吗?

public class Foo {

public int value;

public Foo(int val) {
value = val;
}

@Override
public String toString() {
return "Foo{" + "value=" + value + '}';
}

}

public class Bar {

private ArrayList<Foo> refList;
public Iterable<Foo> overTwentyList;

public Bar() {
refList = new ArrayList<Foo>();
refList.add(new Foo(12));
refList.add(new Foo(23));
refList.add(new Foo(6));
refList.add(new Foo(44));
refList.add(new Foo(2));
refList.add(new Foo(19));
refList.add(new Foo(99));
refList.add(new Foo(74));

overTwentyList = new OverTwenties(refList);
}

class OverTwenties implements Iterable<Foo> {

private final Iterable<Foo> refList;

private OverTwenties(ArrayList<Foo> refList) {
this.refList = refList;
}

@Override
public Iterator<Foo> iterator() {
return new Iterator<Foo>() {
Iterator<Foo> ref = refList.iterator();
Foo next = null;

@Override
public boolean hasNext() {
while (next == null && ref.hasNext()) {
do {
next = ref.hasNext() ? ref.next() : null;
// Skip everything less than 20.
} while (next != null && next.value < 20);
}
return next != null;
}

@Override
public Foo next() {
Foo n = next;
next = null;
return n;
}

};
}

}

}

关于java - 克隆集合成员匹配条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34450477/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com