API:Guava-collections:Lists & Sets & Maps & Range & Table & ImmutableCollections & Ordering

左丘积厚
2023-12-01

1 Lists

package com.collections;

import com.google.common.collect.Lists;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static org.junit.Assert.assertEquals;

public class ListsTest {
    public static void main(String[] args) {
        List<Object> objectList = Lists.newArrayList();

//        testCartesianProduct();
//        testTransform();
//        testNewArrayListWithCapacity();
//        testNewArrayListWithExpectedSize();
//        testReverse();
//        testPartition();

    }

    private static void testPartition() {
        List<String> list = Lists.newArrayList("1", "2", "3", "4");
        List<List<String>> partition = Lists.partition(list, 2);
        List<String> list1 = partition.get(0); // 1 2
        List<String> list2 = partition.get(1); // 3 4
    }

    private static void testReverse() {
        List<Integer> list = Lists.newArrayList(1, 2, 3);
        List<Integer> reverseList = Lists.reverse(list);
        assertEquals(reverseList, Lists.newArrayList(3, 2, 1));
    }

    private static void testNewArrayListWithExpectedSize() {
        List<Integer> list = Lists.newArrayListWithExpectedSize(5);
        assertEquals(list.size(), 0);
    }

    private static void testNewArrayListWithCapacity() {
        /**
         * initialArraySize
         */
        List<Integer> list = Lists.newArrayListWithCapacity(2);
        assertEquals(list.size(), 0);
        IntStream.rangeClosed(1, 3)
                .forEach(list::add);
        System.out.println(list);
    }

    private static void testTransform() {
        List<String> list = Lists.newArrayList(null, "Alex", "Java", "Python");
        List<String> transform = list.stream()
                .filter(Objects::nonNull)
                .map(String::toUpperCase)
                .collect(Collectors.toList());
        System.out.println(transform);
    }

    /**
     * 测试笛卡儿积
     */
    private static void testCartesianProduct() {
        List<List<String>> lists = Lists.cartesianProduct(
                Lists.newArrayList("1", "2"),
                Lists.newArrayList("A", "B")
        );
        System.out.println(lists);
    }
}

2 Sets

package com.collections;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

import java.util.List;
import java.util.Set;

import static org.junit.Assert.assertEquals;

public class SetsTest {
    public static void main(String[] args) {
        /**
         *         Set<Integer> set = new HashSet<Integer>() {{
         *             add(1);
         *             add(2);
         *             add(3);
         *         }};
         */
//        testNewHashSet();
//        testCartesianProduct();
//        testCombinations();
//        testDifference();
//        testIntersection();
//        testUnion();
    }

    private static void testUnion() {
        Sets.SetView<Integer> union = Sets.union(Sets.newHashSet(1, 2, 3),
                Sets.newHashSet(4));
        Set<Integer> set = Sets.newHashSet(union);
        System.out.println(set);
    }

    private static void testIntersection() {
        Sets.SetView<Integer> intersection = Sets.intersection(Sets.newHashSet(1, 2, 3),
                Sets.newHashSet(2));
        Set<Integer> set = Sets.newHashSet(intersection);
        System.out.println(set);
    }

    private static void testDifference() {
        Sets.SetView<Integer> difference = Sets.difference(Sets.newHashSet(1, 2, 3),
                        Sets.newHashSet(2));
        Set<Integer> set = Sets.newHashSet(difference);
        System.out.println(set);
        // [1, 3]
    }

    private static void testCombinations() {
        /**
         * Returns the set of all subsets of set of size size. For example,
         * combinations(ImmutableSet.of(1, 2, 3), 2)
         * returns the set {{1, 2}, {1, 3}, {2, 3}}.
         */
        Set<Set<Integer>> set = Sets.combinations(Sets.newHashSet(1, 2, 3), 2);
        set.forEach(System.out::println);
        /**
         * [1, 2]
         * [1, 3]
         * [2, 3]
         */}

    private static void testCartesianProduct() {
        Set<List<Integer>> set = Sets.cartesianProduct(Sets.newHashSet(1, 2, 3, 1),
                Sets.newHashSet(1, 1, 2));
        assertEquals(set.size(), 6);
        System.out.println(set); // [[1, 1], [1, 2], [2, 1], [2, 2], [3, 1], [3, 2]]
    }

    private static void testNewHashSet() {
        assertEquals(Sets.newHashSet(1, 2, 3, 1).size(), 3);
        assertEquals(Sets.newHashSet(Lists.newArrayList(1, 2, 3, 4, 5, 1)),
                Sets.newHashSet(1, 2, 3, 4, 5));
    }
}

3 Maps

package com.collections;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class MapsTest {
    public static void main(String[] args) {
//        uniqueIndex();
//        asMap();
//        transformValues();
//        filterKeys();
    }

    private static void filterKeys() {
        Set<String> set = Sets.newHashSet("name", "age", "gender");
        Map<String, String> map = Maps.asMap(set, String::toUpperCase);
        /**
         * public static <K, V> Map<K, V> filterKeys(
         *       Map<K, V> unfiltered, final Predicate<? super K> keyPredicate) {}
         */
        Map<String, String> filterKeys = Maps.filterKeys(map, "name"::equals);
        System.out.println(filterKeys);
    }

    private static void transformValues() {
        Set<String> set = Sets.newHashSet("name", "age", "gender");
        Map<String, String> map = Maps.asMap(set, String::toUpperCase);
        /**
         *  public static <K, V1, V2> Map<K, V2> transformValues(
         *       Map<K, V1> fromMap, Function<? super V1, V2> function) {}
         */
        Map<String, String> transformValuesMap = Maps.transformValues(map, e -> e + "_VALUE");
        System.out.println(transformValuesMap); // {name=NAME_VALUE, gender=GENDER_VALUE, age=AGE_VALUE}
    }

    private static void asMap() {
        Set<String> set = Sets.newHashSet("name", "age", "gender");
        /**
         * public static <K, V> Map<K, V> asMap(Set<K> set, Function<? super K, V> function) {}
         */
        Map<String, String> map = Maps.asMap(set, String::toUpperCase);
        System.out.println(map);
    }

    private static void uniqueIndex() {
        List<String> list = Lists.newArrayList("name", "age", "gender");
        /**
         * A Map whose contents will never change, with many other important properties detailed at ImmutableCollection.
         * public static <K, V> ImmutableMap<K, V> uniqueIndex(
         *       Iterable<V> values, Function<? super V, K> keyFunction) {}
         */
        ImmutableMap<String, String> immutableMap = Maps.uniqueIndex(list, String::toUpperCase);
        System.out.println(immutableMap); // {NAME=name, AGE=age, GENDER=gender}
    }
}

4 LinkedHashMultimap & LinkedListMultimap

package com.collections;

import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.LinkedListMultimap;

public class MultiMapsTest {
    public static void main(String[] args) {
//        testLinkedListMultimap();
//        testLinkedHashMultimap();
    }

    private static void testLinkedHashMultimap() {
        LinkedHashMultimap<String, String> map = LinkedHashMultimap.create();
        map.put("1", "1");
        map.put("1", "2");
        System.out.println(map); // {1=[1, 2]}
        map.put("1", "1");
        map.put("1", "2");
        System.out.println(map); // {1=[1, 2]}
    }

    private static void testLinkedListMultimap() {
        LinkedListMultimap<String, String> map = LinkedListMultimap.create();
        map.put("1", "1");
        map.put("1", "2");
        System.out.println(map); // {1=[1, 2]}
        map.put("1", "1");
        map.put("1", "2");
        System.out.println(map); // {1=[1, 2, 1, 2]}
    }
}

5 BiMap

package com.collections;

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;

public class BiMapsTest {
    public static void main(String[] args) {
//        testHashBiMap_1();
//        HashBiMap_2();
//        inverse();
//        forcePut();
    }

    private static void forcePut() {
        HashBiMap<String, String> map = HashBiMap.create();
        map.put("1", "2");
        map.forcePut("3", "2");
        System.out.println(map); // {3=2}
    }

    private static void inverse() {
        HashBiMap<String, String> map = HashBiMap.create();
        map.put("1", "ONE");
        map.put("2", "TWO");
        map.put("3", "THREE");
        System.out.println(map); // {1=ONE, 2=TWO, 3=THREE}
        BiMap<String, String> inverse = map.inverse();
        System.out.println(inverse); // {ONE=1, TWO=2, THREE=3}
    }

    private static void HashBiMap_2() {
        HashBiMap<String, String> map = HashBiMap.create();
        map.put("1", "2");
        map.put("1", "3");
        System.out.println(map); // {1=3}
    }

    private static void testHashBiMap_1() {
        HashBiMap<String, String> map = HashBiMap.create();
        map.put("1", "2");
        map.put("2", "2");
        System.out.println(map); //  value already present: 2
    }
}

6 HashBasedTable

package com.collections;

import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;

import java.util.Map;
import java.util.Set;

/**
 * 二维坐标抽
 *
 * @author zhaoshuai11
 * @date 2022/11/19
 */
public class TableTest {
    public static void main(String[] args) {
        HashBasedTable<String, String, String> table = HashBasedTable.create();
        table.put("language", "java", "1.8");
        table.put("language", "scala", "2.3");
        table.put("language", "python", "3.5");
        table.put("datasource", "mysql", "7.0");
        table.put("datasource", "java", "7.0");

        System.out.println(table); // {language={java=1.8, scala=2.3, python=3.5}, datasource={mysql=7.0, java=7.0}}

        Map<String, String> languageMap = table.row("language");
        Map<String, String> datasourceMap = table.row("datasource");
        System.out.println("datasourceMap = " + datasourceMap); // datasourceMap = {mysql=7.0, java=7.0}
        System.out.println("languageMap = " + languageMap); // languageMap = {java=1.8, scala=2.3, python=3.5}

        String python = languageMap.get("python");
        System.out.println("python = " + python); // python = 3.5

        Map<String, String> java = table.column("java");
        System.out.println(java); // {language=1.8, datasource=7.0}

        Set<Table.Cell<String, String, String>> cellSet = table.cellSet();
        System.out.println(cellSet);
        // [(language,java)=1.8, (language,scala)=2.3, (language,python)=3.5, (datasource,mysql)=7.0, (datasource,java)=7.0]
        cellSet.forEach(e -> System.out.println(e.getRowKey() + " : " + e.getColumnKey() + " : " + e.getValue()));
        /**
         * language : java : 1.8
         * language : scala : 2.3
         * language : python : 3.5
         * datasource : mysql : 7.0
         * datasource : java : 7.0
         */
    }
}

7 Range

package com.collections;


import com.google.common.collect.Maps;
import com.google.common.collect.Range;

import java.util.NavigableMap;
import java.util.TreeMap;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class RangeTest {
    public static void main(String[] args) {
//        closed();
//        open();
//        openClosed();
//        closedOpen();
//        greaterThan();
//        lessThan();
        atLeast();
//        atMost();
//        subMap();

    }

    private static void subMap() {
        TreeMap<String, Integer> treeMap = Maps.newTreeMap();
        treeMap.put("Scala", 1);
        treeMap.put("Guava", 2);
        treeMap.put("Java", 3);
        treeMap.put("Kafka", 4);
        System.out.println(treeMap); // {Guava=2, Java=3, Kafka=4, Scala=1}
        /**
         * public static <K extends Comparable<? super K>, V> NavigableMap<K, V> subMap(
         *       NavigableMap<K, V> map, Range<K> range){}
         */
        NavigableMap<String, Integer> result = Maps.subMap(treeMap, Range.closed("Guava", "Kafka"));
        System.out.println(result); // {Guava=2, Java=3, Kafka=4}
    }

    /**
     * (-∞..100]
     */
    private static void atMost() {
        Range<Integer> range = Range.atMost(100);
        System.out.println(range); // (-∞..100]
    }

    /**
     * [10..+∞)
     */
    private static void atLeast() {
        Range<Integer> range = Range.atLeast(10);
        System.out.println(range); // [10..+∞)

    }

    /**
     * (-∞..10)
     */
    private static void lessThan() {
        Range<Integer> range = Range.lessThan(10);
        System.out.println(range); // (-∞..10)
    }

    /**
     * (10..+∞)
     */
    private static void greaterThan() {
        Range<Integer> range = Range.greaterThan(10);
        System.out.println(range); // (10..+∞)
    }

    /**
     * 0 <= x < 9
     */
    private static void closedOpen() {
        Range<Integer> open = Range.closedOpen(0, 9);
        System.out.println(open); // [0..9)

        assertTrue(open.contains(0));
        assertTrue(open.contains(8));
        assertEquals((int) open.lowerEndpoint(), 0);
        assertEquals((int) open.upperEndpoint(), 9);
    }

    /**
     * 0 < x <= 9
     */
    private static void openClosed() {
        Range<Integer> open = Range.openClosed(0, 9);
        System.out.println(open); // (0..9]

        assertTrue(open.contains(1));
        assertTrue(open.contains(9));
        assertEquals((int) open.lowerEndpoint(), 0);
        assertEquals((int) open.upperEndpoint(), 9);

    }

    /**
     * 0 < x < 9
     */
    private static void open() {
        Range<Integer> open = Range.open(0, 9);
        System.out.println(open); // (0..9)

        assertTrue(open.contains(1));
        assertTrue(open.contains(8));
        assertEquals((int) open.lowerEndpoint(), 0);
        assertEquals((int) open.upperEndpoint(), 9);
    }

    /**
     * 0 <= x <= 9
     */
    private static void closed() {
        Range<Integer> closed = Range.closed(0, 9);
        System.out.println(closed); // [0..9]

        assertTrue(closed.contains(5));
        assertTrue(closed.contains(0));
        assertTrue(closed.contains(9));
        assertEquals((int) closed.lowerEndpoint(), 0);
        assertEquals((int) closed.upperEndpoint(), 9);
    }
}

8 RangeMapTest

package com.collections;

import com.google.common.collect.Range;
import com.google.common.collect.TreeRangeMap;

import static org.junit.Assert.assertEquals;

public class RangeMapTest {
    public static void main(String[] args) {
        TreeRangeMap<Integer, String> gradeScala = TreeRangeMap.create();
        gradeScala.put(Range.closed(0, 59), "A");
        gradeScala.put(Range.closed(60, 69), "B");
        gradeScala.put(Range.closed(70, 79), "C");
        gradeScala.put(Range.closed(80, 89), "D");
        gradeScala.put(Range.closed(90, 100), "E");
        assertEquals(gradeScala.get(97), "E");
    }
}

9 ImmutableCollections

package com.collections;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;

import static org.junit.Assert.assertNotNull;

/**
 * 不可变测试集合
 *
 * @author zhaoshuai11
 * @date 2022/11/19
 */
public class ImmutableCollectionsTest {

    public static void main(String[] args) {
//        immutableList();
//        copyOf();
//        builder();
//        immutableMapOf();
//        immutableMapBuilder();

    }

    private static void immutableMapBuilder() {
        ImmutableMap<String, String> immutableMap =
                ImmutableMap.<String, String>builder().put("Java", "1.8")
                        .put("Scala", "2.0").build();
        System.out.println(immutableMap); // {Java=1.8, Scala=2.0}
    }

    private static void immutableMapOf() {
        ImmutableMap<String, String> immutableMap = ImmutableMap.of("Java", "1.8", "Scala", "2.0");
        System.out.println(immutableMap); // {Java=1.8, Scala=2.0}
    }

    private static void builder() {
        ImmutableList<Object> immutableList = ImmutableList.builder()
                .add(1)
                .add(1, 2, 3, 4)
                .addAll(Lists.newArrayList(2, 2, 3)).build();
        System.out.println(immutableList); // [1, 1, 2, 3, 4, 2, 2, 3]
    }

    private static void copyOf() {
        Integer[] arr = {1, 2, 3, 4, 5};
        ImmutableList<Integer> immutableList = ImmutableList.copyOf(arr);
        System.out.println(immutableList);
    }

    private static void immutableList() {
        ImmutableList<Integer> immutableList = ImmutableList.of(1, 2, 3);
        assertNotNull(immutableList);
        /**
         * Exception in thread "main" java.lang.UnsupportedOperationException
         * 	at com.google.common.collect.ImmutableCollection.add(ImmutableCollection.java:222)
         * 	at com.collections.ImmutableCollectionsTest.main(ImmutableCollectionsTest.java:8)
         */
        immutableList.add(4);
    }
}

10 Ordering

package com.collections;

import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;

import java.util.Collections;
import java.util.List;

public class OrderingTest {
    public static void main(String[] args) {
//        collectionsSort();
//        orderingNatural();

    }

    private static void orderingNatural() {
        List<Integer> list = Lists.newArrayList(1, 5, 3, 8, 2, null);
        Collections.sort(list, Ordering.natural().nullsFirst());
        System.out.println(list); // [null, 1, 2, 3, 5, 8]

        Collections.sort(list, Ordering.natural().nullsFirst().reversed());
        System.out.println(list); // [8, 5, 3, 2, 1, null]
    }

    private static void collectionsSort() {
        List<Integer> list = Lists.newArrayList(1, 5, 3, 8, 2, null);
        /**
         * Exception in thread "main" java.lang.NullPointerException
         */
        Collections.sort(list);
        System.out.println(list);
    }
}

 类似资料: