Collections2 utility example

There are various places around leveluplunch that show the power of guava's Collections2 utility class such as filter a collection, filter null from a collection, predicates example. This example will try to bring it together in one page.

Filter

@Test
public void filter () {
    
    List<String> strings = Lists.newArrayList(
            null, "www", null, 
            "leveluplunch", "com", null);

    
    Collection<String> filterStrings = Collections2.filter(
            strings, new Predicate<String>() {
                @Override
                public boolean apply(String input) {
                    return input != null && input.length() >= 3;
                }
            });

    logger.info(filterStrings);
    
    assertEquals(3, filterStrings.size());
}

Output

[www, leveluplunch, com]

Ordered Permutations

@Test
public void ordered_permutations () {
    
    List<Integer> vals = Lists.newArrayList(1, 2, 3);
    
    Collection<List<Integer>> orderPerm = 
            Collections2.orderedPermutations(vals);
    
    for (List<Integer> val : orderPerm) {
        logger.info(val);
    }

    assertEquals(6, orderPerm.size());
}

Output

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]

Permutations

@Test
public void permutations () {

    List<Integer> vals = Ints.asList(new int[] {1, 2, 3});
    
    Collection<List<Integer>> orderPerm = 
            Collections2.permutations(vals);
    
    for (List<Integer> val : orderPerm) {
        logger.info(val);
    }
    
    assertEquals(6, orderPerm.size());
}

Output

[1, 2, 3]
[1, 3, 2]
[3, 1, 2]
[3, 2, 1]
[2, 3, 1]
[2, 1, 3]

Transform

@Test
public void transform () {
    
    List<String> numbersAsStrings = Lists.newArrayList(
            "1", "2", "3");
    
    Collection<Double> doubles = Collections2.transform(
            numbersAsStrings, new Function<String, Double>() {
        @Override
        public Double apply(String input) {
            return new Double(input);
        }
    });
    
    assertThat(doubles, contains(
             new Double(1), new Double(2), 
             new Double(3)));   
}