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

查看:22
本文介绍了如何在 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>();

这样做的有效方法是什么?

What is the efficient way of doing it?

谢谢.

推荐答案

你可以试试 Apache Commons Collections.

有一个类 CollectionUtils 允许您通过自定义选择或过滤项目 谓词.

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

你的代码应该是这样的:

Your code would be like this:

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天全站免登陆