Lists, Maps and Sets in Google guava tool class are easy to use

Posted by Pests on Thu, 03 Feb 2022 00:44:03 +0100

Google guava

Guava is a supplement to the Java API. It implements the functions commonly used in java development more gracefully, making the coding easier and the code easier to understand. Guava uses a variety of design patterns and has undergone a lot of testing, which is favored by more and more development teams. The latest version of Java API adopts some functions of guava, but it is still irreplaceable.

characteristic

  • Efficient and well-designed API is designed, implemented and used by Google developers
  • Follow efficient java syntax practices
  • Make the code more scale, concise and simple
  • Save time, resources and improve productivity. Guava project contains several core libraries widely relied on by Google's Java project

Core library, for example:

  • Collection [collections]
  • caching
  • Native type support [primitives support]
  • concurrency libraries
  • common annotations
  • string processing
  • I/O, etc.

github address

https://github.com/google/guavahttps://github.com/google/guava

use

Dependency introduction

    <dependencies>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>28.1-jre</version>
        </dependency>
    </dependencies>

Guava collection utility class

Lists

Official website documents:

Lists (Guava: Google Core Libraries for Java 27.0.1-jre API)https://guava.dev/releases/27.0.1-jre/api/docs/com/google/common/collect/Lists.html Corresponding to the List set interface, on COM google. common. Under the collect package

The Lists} interface is declared as follows:

@GwtCompatible(emulated=true)
public final class Lists
    extends Object

Lists class mainly provides static methods for the construction and operation of subclasses of List class. In the lists class, the methods of constructing the # ArrayList, # LinkedList # and # newCopyOnWriteArrayList # objects are supported. The following functions for constructing ArrayList are provided: the following four functions construct an ArrayList object, but do not explicitly give the size of the application space:

newArrayList()
newArrayList(E... elements)
newArrayList(Iterable<? extends E> elements)
newArrayList(Iterator<? extends E> elements)

Testing

        ArrayList<Object> objects = Lists.newArrayList();
        objects.add("Zhang San");
        objects.add(20);
        System.out.println("--- newArrayList test ---");
        System.out.println(objects);
        System.out.println("--- newArrayList test ---");
        ArrayList<Object> objects1 = Lists.newArrayList(objects);
        System.out.println(objects1);
        System.out.println("--- newArrayList test ---");
        ArrayList<String> strings = Lists.newArrayList("Zhang San", "Haidian District, Beijing");
        System.out.println(strings);

The following two functions give the size of space to be allocated when constructing the ArrayList object:

newArrayListWithCapacity(int initialArraySize)
newArrayListWithExpectedSize(int estimatedSize)
        //If you know the number of elements in advance, you can use the newArrayListWithCapacity function; If you can't determine the number of elements, you can use the newArrayListWithExpectedSize function
        //This method simply returns an array of 10.
        ArrayList<Object> objects = Lists.newArrayListWithCapacity(10);
        objects.add("123");
        System.out.println(objects);
        ArrayList<Object> objects1 = Lists.newArrayListWithExpectedSize(10);
        objects1.add("123");
        System.out.println(objects1);

In the # newArrayListWithExpectedSize # function, the # computeArrayListCapacity(int arraySize) function is called. Its implementation is as follows:

@VisibleForTesting 
static int computeArrayListCapacity(int arraySize) {
    checkArgument(arraySize >= 0);
   
  // TODO(kevinb): Figure out the right behavior, and document it
    return Ints.saturatedCast(5L + arraySize + (arraySize / 10));
}

The returned capacity size is , 5L + arraySize + (arraySize / 10). When , arraySize , is relatively large, the ratio of the given size to the actual allocated capacity is 10 / 11.

The Lists # class also supports the construction of # LinkedList and newCopyOnWriteArrayList # objects. Its function interface is:

newLinkedList()
newLinkedList(Iterable<? extends E> elements)   
newCopyOnWriteArrayList()
newCopyOnWriteArrayList(Iterable<? extends E> elements)
       /* newLinkedList()
        newLinkedList(Iterable<? extends E> elements)   
        newCopyOnWriteArrayList()
        newCopyOnWriteArrayList(Iterable<? extends E> elements) */
        LinkedList<Object> objects = Lists.newLinkedList();
        objects.add("Zhang San");
        objects.add("Li Si");
        System.out.println("--- newLinkedList ---");
        System.out.println(objects);
        ArrayList<Object> objects1 = Lists.newArrayList(objects);
        System.out.println("--- newLinkedList ---");
        System.out.println(objects1);
        System.out.println("--- newCopyOnWriteArrayList ---");
        CopyOnWriteArrayList<Object> objects2 = Lists.newCopyOnWriteArrayList();
        objects2.add("Wang Wu");
        objects2.add("Zhang San");
        System.out.println(objects2);
        System.out.println("--- newCopyOnWriteArrayList ---");
        CopyOnWriteArrayList<Object> objects3 = Lists.newCopyOnWriteArrayList(objects2);
        System.out.println(objects3);

 

We can also store two (or three) data of the same type in a list, which can be passed into functions with only one parameter or functions that need to reduce parameters. These functions are as follows:

asList(@Nullable E first, E[] rest)
asList(@Nullable E first, @Nullable E second, E[] rest)
        String str = "i love u";
        String[] strs = {"i like u", "i miss u"};
        List<String> strings = Lists.asList(str, strs);
        System.out.println(strings);

 

The "transform" function in the "Lists" class can process "fromList" according to the "function" passed in, and store the processing results into a new list object, which is conducive to our analysis. The function interface is as follows:

public static <F, T> List<T> transform(List<F> fromList, Function<? super F, ? extends T> function)

        Function<String, Integer> strlen = new Function<String, Integer>() {
            public Integer apply(String from) {
                Preconditions.checkNotNull(from);
                return from.length();
            }
        };

        List<String> from = Lists.newArrayList("abc", "defg", "hijkl");
        List<Integer> to = Lists.transform(from, strlen);
        for (int i = 0; i < from.size(); i++) {
            System.out.printf("%s has length %d\n", from.get(i), to.get(i));
        }

 

 

Maps

Official documents

Maps (Guava: Google Core Libraries for Java 27.0.1-jre API)https://guava.dev/releases/27.0.1-jre/api/docs/com/google/common/collect/Maps.html  com. google. common. collect. Declaration of maps} interface:

@GwtCompatible(emulated=true)
public final class Maps
    extends Object
newHashMap
newHashMapWithExpectedSize
newLinkedHashMap 
ImmutableMap
difference
transformValues

test

newHashMap

        HashMap<Object, Object> hashMap = Maps.newHashMap();
        for (int i = 0; i < 10; i++) {
            hashMap.put(i, i);
        }
        System.out.println("hashMap: " + hashMap);
        HashMap<Object, Object> hashMap1 = Maps.newHashMap(hashMap);
        System.out.println("hashMap1: " + hashMap1);

 newHashMapWithExpectedSize

        Map<Integer, Integer> map = Maps.newHashMapWithExpectedSize(3);
        map.put(1, 1);
        map.put(2, 2);
        map.put(3, 3);
        System.out.println("map: " + map);     // map: {1=1, 2=2, 3=3}

 

 newLinkedHashMap

        Map<Integer, Integer> map = Maps.newLinkedHashMap();
        map.put(11, 11);
        System.out.println("map: " + map);
        LinkedHashMap<Integer, Integer> map1 = Maps.newLinkedHashMap(map);
        System.out.println("map1: " + map1);

 

 ImmutableMap

        ImmutableMap<String, String> a = ImmutableMap.of("a", "1");
        System.out.println(a);

 

difference

        Map<Integer, Integer> map = Maps.newHashMap();
        map.put(10, 10);
        Map<Integer, Integer> map1 = Maps.newHashMap();
        map1.put(10, 10);
        map1.put(20, 20);
        MapDifference<Integer, Integer> difference = Maps.difference(map, map1);
        System.out.println(difference.areEqual());
        System.out.println(difference.entriesInCommon());
        System.out.println(difference.entriesOnlyOnRight());
        System.out.println(difference.entriesOnlyOnLeft());
        System.out.println(difference.entriesDiffering());
        System.out.println(difference);

transformValues

        Map<String, Boolean> fromMap = Maps.newHashMap();
        fromMap.put("key", true);
        fromMap.put("value", false);
        // Negate the incoming element
        System.out.println(Maps.transformValues(fromMap, (Function<Boolean, Object>) input -> !input));

        // If value is false, key will be capitalized
        Maps.EntryTransformer<String, Boolean, String> entryTransformer = (key, value) -> value ? key : key.toUpperCase();
        System.out.println(Maps.transformEntries(fromMap, entryTransformer));

 

Sets 

Official documents

Sets (Guava: Google Core Libraries for Java 27.0.1-jre API)https://guava.dev/releases/27.0.1-jre/api/docs/com/google/common/collect/Sets.html com. google. common. collect. Declaration of sets} interface:

@GwtCompatible(emulated=true)
public final class Sets
    extends Object
newHashSet
filter
difference
symmetricDifference
intersection
union
cartesianProduct
powerSet

newHashSet

        HashSet<Object> objects = Sets.newHashSet();
        objects.add("Zhang San");
        objects.add("Li Si");
        System.out.println(objects);

 

filter

    /**
     * filter: Returns the element Set that satisfies the given Predicate in the incoming Set unfiltered
     */
    @Test
    public void testFilter() {
        Set<String> set = Sets.newHashSet("i like u", "i miss u", "i love u");
        Predicate<String> predicate = new Predicate<String>() {
            @Override
            public boolean apply(String input) {
                //Filter elements that contain the letter l
                return input.contains("l");
            }
        };
        System.out.println(Sets.filter(set, predicate));                        // [i like u, i love u]
        System.out.println(Sets.filter(set, input -> input.contains("l")));     // [i like u, i love u]
    }

difference

    /**
     * difference: Non modifiable SetView that returns the difference between two sets
     * A,B If there are two sets, the set composed of all elements belonging to A and not belonging to B is called the difference set of A and B
     */
    @Test
    public void testDifference() {
        Set<Integer> set1 = Sets.newHashSet(1, 2, 3, 4, 5);
        Set<Integer> set2 = Sets.newHashSet(1, 3, 5, 7, 9);
        System.out.println(Sets.difference(set1, set2));        // [2, 4]
    }

 

symmetricDifference

    /**
     * symmetricDifference: An unmodifiable SetView that returns the symmetry difference between two sets
     * Symmetry difference, that is, the symmetry difference between two sets, is a set composed of elements belonging to only one set and not to the other set
     */
    @Test
    public void testSymmetricDifference() {
        Set<Integer> set1 = Sets.newHashSet(1, 2, 3, 4, 5);
        Set<Integer> set2 = Sets.newHashSet(1, 3, 5, 7, 9);
        System.out.println(Sets.symmetricDifference(set1, set2));       // [2, 4, 9, 7]
    }

 

intersection

    /**
     * intersection: Returns a non modifiable SetView of the intersection of two set sets
     * The intersection of two sets A and B refers to A set containing all elements belonging to both A and B without other elements
     */
    @Test
    public void testIntersection() {
        Set<Integer> set1 = Sets.newHashSet(1, 2, 3, 4, 5);
        Set<Integer> set2 = Sets.newHashSet(1, 3, 5, 7, 9);
        System.out.println(Sets.intersection(set1, set2));      // [1, 3, 5]
    }

Union

    /**
     * Union: Returns a non modifiable SetView of the union of two sets
     * If A and B are sets, the union of A and B is A set with all elements of A and all elements of B, but no other elements
     */
    @Test
    public void testUnion() {
        Set<Integer> set1 = Sets.newHashSet(1, 2, 3, 4, 5);
        Set<Integer> set2 = Sets.newHashSet(1, 3, 5, 7, 9);
        System.out.println(Sets.union(set1, set2));     // [1, 2, 3, 4, 5, 9, 7]
    }

 cartesianProduct

    /**
     * cartesianProduct: Returns each possible set formed by selecting an element from each given set
     */
    @Test
    public void testCartesianProduct() {
        Set<String> set1 = Sets.newHashSet("i love u", "i hate u");
        Set<String> set2 = Sets.newHashSet("tom", "jerry");
        Set<List<String>> sets = Sets.cartesianProduct(set1, set2);
        System.out.println(sets);       // [[i hate u, tom], [i hate u, jerry], [i love u, tom], [i love u, jerry]]
    }

powerSet

    /**
     * powerSet: Returns a set containing all possible parent sets of a given set
     */
    @Test
    public void testPowerSet() {
        Set<String> set1 = Sets.newHashSet("A", "B", "C");
        Set<Set<String>> sets = Sets.powerSet(set1);
//        for (Set<String> set : sets) {
//            System.out.println(set);
//        }
        System.out.println(Arrays.toString(sets.toArray()));    // [[], [A], [B], [A, B], [C], [A, C], [B, C], [A, B, C]]
    }

Complete code

Unit testing with junit in maven project

import com.google.common.base.Predicate;
import com.google.common.collect.Sets;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

public class TestSets {
    /**
     * filter: Returns the element Set that satisfies the given Predicate in the incoming Set unfiltered
     */
    @Test
    public void testFilter() {
        Set<String> set = Sets.newHashSet("i like u", "i miss u", "i love u");
        Predicate<String> predicate = new Predicate<String>() {
            @Override
            public boolean apply(String input) {
                //Filter elements that contain the letter l
                return input.contains("l");
            }
        };
        System.out.println(Sets.filter(set, predicate));                        // [i like u, i love u]
        System.out.println(Sets.filter(set, input -> input.contains("l")));     // [i like u, i love u]
    }

    /**
     * difference: Non modifiable SetView that returns the difference between two sets
     * A,B If there are two sets, the set composed of all elements belonging to A and not belonging to B is called the difference set of A and B
     */
    @Test
    public void testDifference() {
        Set<Integer> set1 = Sets.newHashSet(1, 2, 3, 4, 5);
        Set<Integer> set2 = Sets.newHashSet(1, 3, 5, 7, 9);
        System.out.println(Sets.difference(set1, set2));        // [2, 4]
    }

    /**
     * symmetricDifference: An unmodifiable SetView that returns the symmetry difference between two sets
     * Symmetry difference, that is, the symmetry difference between two sets, is a set composed of elements belonging to only one set and not to the other set
     */
    @Test
    public void testSymmetricDifference() {
        Set<Integer> set1 = Sets.newHashSet(1, 2, 3, 4, 5);
        Set<Integer> set2 = Sets.newHashSet(1, 3, 5, 7, 9);
        System.out.println(Sets.symmetricDifference(set1, set2));       // [2, 4, 9, 7]
    }


    /**
     * intersection: Returns a non modifiable SetView of the intersection of two set sets
     * The intersection of two sets A and B refers to A set containing all elements belonging to both A and B without other elements
     */
    @Test
    public void testIntersection() {
        Set<Integer> set1 = Sets.newHashSet(1, 2, 3, 4, 5);
        Set<Integer> set2 = Sets.newHashSet(1, 3, 5, 7, 9);
        System.out.println(Sets.intersection(set1, set2));      // [1, 3, 5]
    }

    /**
     * Union: Returns a non modifiable SetView of the union of two sets
     * If A and B are sets, the union of A and B is A set with all elements of A and all elements of B, but no other elements
     */
    @Test
    public void testUnion() {
        Set<Integer> set1 = Sets.newHashSet(1, 2, 3, 4, 5);
        Set<Integer> set2 = Sets.newHashSet(1, 3, 5, 7, 9);
        System.out.println(Sets.union(set1, set2));     // [1, 2, 3, 4, 5, 9, 7]
    }

    /**
     * cartesianProduct: Returns each possible set formed by selecting an element from each given set
     */
    @Test
    public void testCartesianProduct() {
        Set<String> set1 = Sets.newHashSet("i love u", "i hate u");
        Set<String> set2 = Sets.newHashSet("tom", "jerry");
        Set<List<String>> sets = Sets.cartesianProduct(set1, set2);
        System.out.println(sets);       // [[i hate u, tom], [i hate u, jerry], [i love u, tom], [i love u, jerry]]
    }

    /**
     * powerSet: Returns a set containing all possible parent sets of a given set
     */
    @Test
    public void testPowerSet() {
        Set<String> set1 = Sets.newHashSet("A", "B", "C");
        Set<Set<String>> sets = Sets.powerSet(set1);
//        for (Set<String> set : sets) {
//            System.out.println(set);
//        }
        System.out.println(Arrays.toString(sets.toArray()));    // [[], [A], [B], [A, B], [C], [A, C], [B, C], [A, B, C]]
    }

}

Topics: Java Google set IDE