Filter collections containing text using Google Guava

350 Views Asked by At

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.

3

There are 3 best solutions below

0
On

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]
0
On

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}

0
On

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.