简体   繁体   中英

Filter collections containing text using Google Guava

I'm using a ImmutableList data structure. What's the best way to filter the contents of the list and return all the elements containing that term in the description attribute of the inventory.

If you're into Java 8, try this:

ImmutableList<String> immutableList = ImmutableList.of("s1", "s2");
List<Object> collect = immutableList.stream().filter(s -> s.endsWith("1")).collect(Collectors.toList());
// collect: [s1]

My solution: You need to write one predicate which can accept an argument. Then filter your collection with it.

public static void main(String args[])  {

    Item i1 = new Item("Pen", "To write...");
    Item i2 = new Item("Phone","to call someone..." );

    List<Item> items = new ArrayList<Item>();

    items.add(i2);
    items.add(i1);

    Collection<Item> result = Collections2.filter(items, filterDescription("To write..."));

    for(Item item : result){
        System.out.println(item);
    }

}

Method takes an argument and turns a predicate

public static Predicate<Item> filterDescription(final String desciption){
    return new Predicate<Item>() {

        @Override
        public boolean apply(Item input) {
           return input.getDescription() != null && input.getDescription().contains(desciption);
        }
    };
}

Result:

--- exec-maven-plugin:1.2.1:exec (default-cli) @ App ---

Item{description=To write..., title=Pen, price=0.0, count=0}

With FluentIterable:

final String description = "search string";
final Iterable<Item> filtered = FluentIterable.from(unfiltered)
        .filter(new Predicate<Item>() {
            @Override
            public boolean apply(final Item input) {
               return input.getDescription().contains(desciption);
            }
        });

You can chain filters, transforms (etc) with FluentIterable. If you want to end up with a list or a set, just add ".toList()" or ".toSet()" at the end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM