如何在Java对象列表中搜索 [英] How to search in a List of Java object

查看:338
本文介绍了如何在Java对象列表中搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象列表,列表是非常大的。对象是

I have a List of object and the list is very big. The object is

class Sample {
    String value1;
    String value2;
    String value3;
    String value4;
    String value5;
 }



现在我必须在列表中搜索对象的特定值。如果 value3 =='three'我必须返回这些对象(我的搜索不总是基于value3)

Now I have to search for a specific value of an object in the list. Say if value3=='three' I have to return those objects (My search is not always based on value3)

列表是

List<Sample> list = new ArrayList<Sample>();

有效的方法是什么?

感谢。

推荐答案

您可以尝试 Apache Commons Collections

有一个类 CollectionUtils ,允许您通过自定义谓词

There is a class CollectionUtils that allows you to select or filter items by custom Predicate.

您的代码将是这样:

Predicate condition = new Predicate() {
   boolean evaluate(Object sample) {
        return ((Sample)sample).value3.equals("three");
   }
};
List result = CollectionUtils.select( list, condition );

更新

java8 中,使用Lambdas和 StreamAPI 这应该是:

In java8, using Lambdas and StreamAPI this should be:

List<Sample> result = list.stream()
     .filter(item -> item.value3.equals("three"))
     .collect(Collectors.toList());

太棒了!

这篇关于如何在Java对象列表中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆