java元素过滤,从Java中的集合中过滤元素的简单方法? (Easy way to filter elements from a collection in Java?)...

最佳答案

英文原文

You can use CollectionUtils.filter(). It works with an Iterator, so it should have no problems removing items directly from the Collection. It is another dependency though. If you want the code standalone it would be:

public interface Predicate {

boolean evaluate(Object o);

}

public static void filter(Collection collection, Predicate predicate) {

if ((collection != null) && (predicate != null))

for (Iterator it = collection.iterator(); it.hasNext(); )

if (!predicate.evaluate(it.next()))

it.remove();

}

...

filter(collection, new Predicate() {

public boolean evaluate(Object o) { return whatever; }

});

中文翻译

您可以使用CollectionUtils.filter()。它适用于Iterator,因此直接从Collection中删除项目应该没有问题。这是另一种依赖。如果您希望代码独立,那就是:

public interface Predicate {

boolean evaluate(Object o);

}

public static void filter(Collection collection,Predicate predicate){

if((collection!= null)&&(predicate!= null))

for(Iterator it = collection.iterator(); it.hasNext();)

if(!predicate.evaluate(it.next()))

it.remove();

}

...

filter(collection,new Predicate(){

public boolean evaluate(Object o){return whatever; }

});

You can use CollectionUtils.filter(). It works with an Iterator, so it should have no problems removing items directly from the Collection. It is another dependency though. If you want the code standalone it would be:

public interface Predicate {

boolean evaluate(Object o);

}

public static void filter(Collection collection, Predicate predicate) {

if ((collection != null) && (predicate != null))

for (Iterator it = collection.iterator(); it.hasNext(); )

if (!predicate.evaluate(it.next()))

it.remove();

}

...

filter(collection, new Predicate() {

public boolean evaluate(Object o) { return whatever; }

});

您可以使用CollectionUtils.filter()。它适用于Iterator,因此直接从Collection中删除项目应该没有问题。这是另一种依赖。如果您希望代码独立,那就是:

public interface Predicate {

boolean evaluate(Object o);

}

public static void filter(Collection collection,Predicate predicate){

if((collection!= null)&&(predicate!= null))

for(Iterator it = collection.iterator(); it.hasNext();)

if(!predicate.evaluate(it.next()))

it.remove();

}

...

filter(collection,new Predicate(){

public boolean evaluate(Object o){return whatever; }

});

参考答案2

See if lambdaj's filter option can help you.

参考答案3

You could always go backwards and delete the elements..

for (int i = array.size() - 1; i >= 0; i--) {

if (array.get(i).getCarColor() == Color.BLUE)

array.remove(i);

}

edit: Noticed it was a LinkedList which might make my answer a bit non-relevant.

参考答案4

I'm a big fan of the Iterator solution provided by Vivien Barousse and gpeche. But I wanted to point out that you don't have to actually remove any elements from the collection, you just need to prevent the filter from returning them. That way, you basically have multiple views of the same collection, which can be very convenient and efficient. The Filter object is basically your lamda expression, or as close as you're gonna get in Java until version 7...

参考答案5

You could iterate through the list using a ListIterator, which has a remove method.

Btw you should declare your list as List - program for interfaces, not implementation.

参考答案6

Maybe you could use iterators, which are a little more efficient:

public void removeAllBlueCars() {

Iterator carsIterator = cars.iterator();

while (carsIterator.hasNext()) {

Car c = carsIterator.next();

if (c.getCarColor() == Color.BLUE) {

carsIterator.remove();

}

}

}

Also, if you want to make this solution more generic, I'd suggest you something like:

public interface Filter {

public boolean shouldRemove(T t);

}

And you could use it like this:

public void removeCars(Filter filter) {

Iterator carsIterator = cars.iterator();

while (carsIterator.hasNext()) {

Car c = carsIterator.next();

if (filter.shouldRemove(c)) {

carsIterator.remove();

}

}

}

Your method gets called like this:

removeCars(new Filter() {

public boolean shouldRemove(Car car) {

return car.getCarColor() == Color.BLUE;

}

});

参考答案7

With Java 8, you can filter with a lambda expression using Collection.removeIf.

cars.removeIf(c -> c.getCarColor() == Color.BLUE);

参考答案8

For those of you who come across this thread and might be working on Android with RxJava/RxAndroid, there's a quick way to do this without adding the Apache Commons Collections dependency:

cars = Observable.from(cars).filter(car -> {

if (car.getCarColor() == Color.BLUE) {

return false;

}

return true;

}).toList().toBlocking().first();

Note that I also happen to be using lambda expressions with Retrolambda. If you aren't using Retrolambda, you can express the same thing using the following:

cars = Observable.from(cars).filter(new Func1() {

@Override

public Boolean call(Car car) {

if (car.getCarColor() == Color.BLUE) {

return false;

}

return true;

}

}).toList().toBlocking().first();

参考答案9

It's really an old post but how abt using the way given in Oracle Java tutorial.

static void filter(Collection>c) {

for (Iterator>it = c.iterator(); it.hasNext(); )

if (!cond(it.next()))

it.remove();

}

参考答案10

Here is the Android way to implement a generic solution for this:

Usage:

Remove all null strings from my list

LinkedList list = ...

ListUtils.filter(list, new ListUtils.Filter() {

@Override

public boolean keepItem(String item) {

return item != null;

}

});

Source:

public class ListUtils {

public interface Filter{

boolean keepItem(T item);

}

public static void filter(@NonNull List items, @NonNull Filter filter) {

for (Iterator iterator = items.iterator(); iterator.hasNext();){

if(!filter.keepItem(iterator.next())){

iterator.remove();

}

}

}

}

参考答案11

public static void filter(List list, Predicate super T> removeIf) {

if(list == null) return;

Iterator iterator = list.iterator();

while (iterator.hasNext()) {

if (removeIf.apply(iterator.next())) iterator.remove();

}

}

Pass a list of some generic type to this function with a predicate to remove unwanted elements.

参考答案12

With Java8 introducing lambda expressions, it's much easier to implement filtering on a collection in a more functional approach.

I wrote an example for you. Please also note how nicer it is to print Collection content using forEach:

public class Java8Filtering {

public static void main(String[] argc) {

LinkedList cars = new LinkedList<>();

cars.add(new Car("car 1", Color.BLUE));

cars.add(new Car("car 2", Color.GREEN));

cars.add(new Car("car 3", Color.RED));

cars.add(new Car("car 4", Color.BLUE));

List filteredCars = cars.stream()

.filter(car -> car.getCarColor() != Color.BLUE)

.collect(Collectors.toList());

filteredCars.forEach(car -> System.out.println("Car: " + car.getCarName() + " with color: " + car.getCarColor()));

}

}

class Car {

private Color carColor;

private String carName;

public Car(String carName, Color carColor) {

this.carName = carName;

this.carColor = carColor;

}

public Color getCarColor() {

return carColor;

}

public void setCarColor(Color carColor) {

this.carColor = carColor;

}

public String getCarName() {

return carName;

}

public void setCarName(String carName) {

this.carName = carName;

}

}

enum Color {

BLUE, GREEN, RED

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值