-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathGuava-Collection.html
1 lines (1 loc) · 101 KB
/
Guava-Collection.html
1
<!-- build time:Wed Mar 09 2022 10:17:49 GMT+0800 (GMT+08:00) --><!doctype html><html class="theme-next mist" lang="zh-Hans"><head><meta name="generator" content="Hexo 3.8.0"><meta name="google-site-verification" content="7Tau9WyVgxnsEY9oYedu9g0U6_8akOX3wiKbaYcrg9A"><meta name="baidu-site-verification" content="EVwLiaxdxX"><link href="/css/xps13.css" rel="stylesheet" type="text/css"><link href="/css/message.css" rel="stylesheet" type="text/css"><link href="//fonts.googleapis.com/css?family=Baloo+Bhaijaan|Inconsolata|Josefin+Sans|Montserrat" rel="stylesheet"><script type="text/javascript" src="/js/jquery-1.11.3.min.js"></script><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1"><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css"><link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css"><meta name="keywords" content="guava,"><link rel="alternate" href="/atom.xml" title="MrBird" type="application/atom+xml"><link rel="shortcut icon" type="image/x-icon" href="/bird.png?v=5.1.1"><meta name="description" content="不可变集合不可变集合例子:12ImmutableSet&lt;String&gt; FRUITS = ImmutableSet.of("apple", "watermelon", "cherry", "mango");FRUITS.remove("apple");将抛出java.lang.UnsupportedOperationException异常:"><meta name="keywords" content="guava"><meta property="og:type" content="article"><meta property="og:title" content="Guava 集合操作"><meta property="og:url" content="http://mrbird.cc/Guava-Collection.html"><meta property="og:site_name" content="MrBird"><meta property="og:description" content="不可变集合不可变集合例子:12ImmutableSet&lt;String&gt; FRUITS = ImmutableSet.of("apple", "watermelon", "cherry", "mango");FRUITS.remove("apple");将抛出java.lang.UnsupportedOperationException异常:"><meta property="og:locale" content="zh-Hans"><meta property="og:image" content="http://mrbird.cc/img/febsvue/QQ截图20190422144849.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190422172835.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190423231111.png"><meta property="og:image" content="http://mrbird.cc/img/QQ图片20190423231252.png"><meta property="og:updated_time" content="2020-03-20T06:57:21.983Z"><meta name="twitter:card" content="summary"><meta name="twitter:title" content="Guava 集合操作"><meta name="twitter:description" content="不可变集合不可变集合例子:12ImmutableSet&lt;String&gt; FRUITS = ImmutableSet.of("apple", "watermelon", "cherry", "mango");FRUITS.remove("apple");将抛出java.lang.UnsupportedOperationException异常:"><meta name="twitter:image" content="http://mrbird.cc/img/febsvue/QQ截图20190422144849.png"><script type="text/javascript" id="hexo.configurations">var NexT=window.NexT||{},CONFIG={root:"/",scheme:"Mist",sidebar:{position:"left",display:"always",offset:12,offset_float:0,b2t:!1,scrollpercent:!0},fancybox:!1,motion:!1}</script><title>Guava 集合操作 | MrBird</title></head><body ondragstart="return!1" class="animsition" lang="zh-Hans" style="overflow-x:hidden;padding-left:280px"><script type="text/javascript" src="/js/mo.min.js"></script><style>body{text-rendering:geometricPrecision!important;font-family:'Josefin Sans','PingFang SC'!important;-webkit-font-smoothing:antialiased!important;-webkit-text-size-adjust:100%!important;background-color:#f4f6f7}@media (min-width:768px) and (max-width:991px){body .header-innerr{width:700px!important}}.header-innerr{margin:0 auto;padding:100px 0 70px;width:880px}@media (min-width:1600px){.container .header-innerr{width:996px}}.header-innerr{position:relative}.header-innerr{padding:0}.header-innerr:after,.header-innerr:before{content:" ";display:table}.header-innerr:after{clear:both}@media (max-width:767px){.header-innerr{width:auto;padding:10px;margin-bottom:-20px}}</style><div class="container sidebar-position-left page-post-detail"><div class="headband"></div><header id="header" class="header"><div class="header-inner"><div class="site-brand-wrapper"><div class="site-meta"><link href="https://fonts.font.im/css?family=Merienda" rel="stylesheet"><div class="custom-logo-site-title"></div><h1 class="site-subtitle" itemprop="description"></h1></div><div class="site-nav-toggle"><button><span class="btn-bar"></span> <span class="btn-bar"></span> <span class="btn-bar"></span></button></div></div><nav class="site-nav"><div class="site-search"><div class="popup search-popup local-search-popup"><div class="local-search-header clearfix"><span class="search-icon"><i class="fa fa-search"></i> </span><span class="popup-btn-close"><i class="fa fa-times-circle"></i></span><div class="local-search-input-wrapper"><input autocomplete="off" placeholder="Search" spellcheck="false" type="text" id="local-search-input"></div></div><div id="local-search-result"></div></div></div></nav></div><div class="header-innerr"></div></header><main id="main" class="main"><div class="main-inner"><div class="content-wrap"><div id="content" class="content"><div id="posts" class="posts-expand"><article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"><link itemprop="mainEntityOfPage" href="http://mrbird.cc/Guava-Collection.html"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="name" content="MrBird"><meta itemprop="description" content=""><meta itemprop="image" content="/images/blogImage.jpg"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="MrBird"></span><header class="post-header"><h2 class="post-title" itemprop="name headline">Guava 集合操作</h2><div class="post-meta"><span class="post-time"><span class="post-meta-item-icon"><i class="fa fa-calendar-o"></i> </span><span class="post-meta-item-text"></span> <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-01-05T14:05:25+08:00">2019-01-05 </time></span><span></span> <span class="post-meta-divider">|</span> <span class="page-pv"><i class="fa fa-laptop"></i> Visit count <span class="busuanzi-value" id="busuanzi_value_page_pv"></span></span></div></header><div class="post-body" itemprop="articleBody"><h2 id="不可变集合"><a href="#不可变集合" class="headerlink" title="不可变集合"></a>不可变集合</h2><p>不可变集合例子:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ImmutableSet<String> FRUITS = ImmutableSet.of(<span class="string">"apple"</span>, <span class="string">"watermelon"</span>, <span class="string">"cherry"</span>, <span class="string">"mango"</span>);</span><br><span class="line">FRUITS.remove(<span class="string">"apple"</span>);</span><br></pre></td></tr></table></figure><p></p><p>将抛出<code>java.lang.UnsupportedOperationException</code>异常:<a id="more"></a> <img src="img/febsvue/QQ截图20190422144849.png" alt="QQ截图20190422144849.png"></p><h3 id="创建不可变集合"><a href="#创建不可变集合" class="headerlink" title="创建不可变集合"></a>创建不可变集合</h3><p><strong>of</strong></p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ImmutableList<String> immutableList = ImmutableList.of(<span class="string">"a"</span>, <span class="string">"b"</span>, <span class="string">"c"</span>);</span><br><span class="line">ImmutableMap<Integer, String> immutableMap = ImmutableMap.of(<span class="number">1</span>, <span class="string">"v1"</span>, <span class="number">2</span>, <span class="string">"v2"</span>, <span class="number">3</span>, <span class="string">"v3"</span>)</span><br></pre></td></tr></table></figure><p></p><p><strong>copyOf</strong></p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Map<String, String> map = Maps.newHashMap();</span><br><span class="line">ImmutableMap<String, String> immutableMap = ImmutableMap.copyOf(map);</span><br></pre></td></tr></table></figure><p></p><p><strong>builder</strong></p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">Map<String, String> map = Maps.newHashMap();</span><br><span class="line">ImmutableMap<String, String> immutableMap = ImmutableMap.<String, String>builder()</span><br><span class="line"> .putAll(map)</span><br><span class="line"> .put(<span class="string">"k1"</span>, <span class="string">"v1"</span>)</span><br><span class="line"> .build();</span><br><span class="line"></span><br><span class="line">List<String> list = Lists.newArrayList();</span><br><span class="line">ImmutableList<String> immutableList = ImmutableList.<String>builder()</span><br><span class="line"> .addAll(list)</span><br><span class="line"> .build();</span><br></pre></td></tr></table></figure><p></p><p>除此之外,我们也可以从Java 8 Stream中创建不可变集合:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="keyword">static</span> java.util.stream.Collectors.*;</span><br><span class="line">...</span><br><span class="line"></span><br><span class="line">List<String> list = Arrays.asList(<span class="string">"a"</span>, <span class="string">"b"</span>, <span class="string">"c"</span>);</span><br><span class="line">List<String> immutableList = list.stream()</span><br><span class="line"> .collect(collectingAndThen(toList(), ImmutableList::copyOf));</span><br><span class="line"></span><br><span class="line">System.out.println(immutableList.getClass()); <span class="comment">// class com.google.common.collect.RegularImmutableList</span></span><br></pre></td></tr></table></figure><p></p><p>上面的例子我们也可以使用Guava提供的收集器:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">List<String> list = Arrays.asList(<span class="string">"a"</span>, <span class="string">"b"</span>, <span class="string">"c"</span>);</span><br><span class="line">List<String> immutableList = list.stream()</span><br><span class="line"> .collect(ImmutableList.toImmutableList());</span><br><span class="line"></span><br><span class="line">System.out.println(immutableList.getClass()); <span class="comment">// class com.google.common.collect.RegularImmutableList</span></span><br></pre></td></tr></table></figure><p></p><h3 id="不可变集合优点"><a href="#不可变集合优点" class="headerlink" title="不可变集合优点"></a>不可变集合优点</h3><ol><li><p>当对象被不可信的库调用时,不可变形式是安全的;</p></li><li><p>不可变对象被多个线程调用时,不存在竞态条件问题</p></li><li><p>不可变集合不需要考虑变化,因此可以节省时间和空间。所有不可变的集合都比它们的可变形式有更好的内存利用率(分析和测试细节);</p></li><li><p>不可变对象因为有固定不变,可以作为常量来安全使用。</p></li></ol><h2 id="新集合类型"><a href="#新集合类型" class="headerlink" title="新集合类型"></a>新集合类型</h2><p>Guava提供了许多JDK没有的集合类型。</p><h3 id="RangeSet"><a href="#RangeSet" class="headerlink" title="RangeSet"></a>RangeSet</h3><p>RangeSet一组不相连的、非空的区间,基本实现为TreeRangeSet,看个RangeSet的例子:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">RangeSet<Integer> rangeSet = TreeRangeSet.create();</span><br><span class="line">rangeSet.add(Range.closed(<span class="number">1</span>, <span class="number">10</span>));</span><br><span class="line">System.out.println(rangeSet); <span class="comment">// [[1..10]]</span></span><br><span class="line"></span><br><span class="line">rangeSet.add(Range.closedOpen(<span class="number">11</span>, <span class="number">15</span>));</span><br><span class="line">System.out.println(rangeSet); <span class="comment">// 不相连区间 [[1..10], [11..15)]</span></span><br><span class="line"></span><br><span class="line">rangeSet.add(Range.closedOpen(<span class="number">15</span>, <span class="number">20</span>));</span><br><span class="line">System.out.println(rangeSet); <span class="comment">// 相连区间 [[1..10], [11..20)]</span></span><br><span class="line"></span><br><span class="line">rangeSet.add(Range.openClosed(<span class="number">0</span>, <span class="number">0</span>));</span><br><span class="line">System.out.println(rangeSet); <span class="comment">// 空区间 [[1..10], [11..20)]</span></span><br><span class="line"></span><br><span class="line">rangeSet.remove(Range.open(<span class="number">5</span>, <span class="number">10</span>)); </span><br><span class="line">System.out.println(rangeSet); <span class="comment">// 区间分割 [[1..5], [10..10], [11..20)]</span></span><br></pre></td></tr></table></figure><p></p><p>查看RangeSet的范围跨度:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">RangeSet<Integer> rangeSet = TreeRangeSet.create();</span><br><span class="line">rangeSet.add(Range.closed(<span class="number">1</span>, <span class="number">10</span>));</span><br><span class="line">rangeSet.add(Range.closedOpen(<span class="number">11</span>, <span class="number">15</span>));</span><br><span class="line"></span><br><span class="line">Range<Integer> span = rangeSet.span();</span><br><span class="line">System.out.println(span.lowerEndpoint().intValue()); <span class="comment">// 1</span></span><br><span class="line">System.out.println(span.upperEndpoint().intValue()); <span class="comment">// 15</span></span><br></pre></td></tr></table></figure><p></p><p>从已有的RangeSet获取一个子范围RangeSet:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">RangeSet<Integer> numberRangeSet = TreeRangeSet.create();</span><br><span class="line"></span><br><span class="line">numberRangeSet.add(Range.closed(<span class="number">0</span>, <span class="number">2</span>));</span><br><span class="line">numberRangeSet.add(Range.closed(<span class="number">3</span>, <span class="number">5</span>));</span><br><span class="line">numberRangeSet.add(Range.closed(<span class="number">5</span>, <span class="number">8</span>));</span><br><span class="line">RangeSet<Integer> numberSubRangeSet = numberRangeSet.subRangeSet(Range.closed(<span class="number">4</span>, <span class="number">14</span>));</span><br><span class="line"></span><br><span class="line">System.out.println(numberRangeSet); <span class="comment">// [[0..2], [3..8]]</span></span><br><span class="line">System.out.println(numberSubRangeSet); <span class="comment">// [[4..8]]</span></span><br></pre></td></tr></table></figure><p></p><p>获取除了RangeSet范围外的RangeSet:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">RangeSet<Integer> numberRangeSet = TreeRangeSet.create();</span><br><span class="line"></span><br><span class="line">numberRangeSet.add(Range.closed(<span class="number">0</span>, <span class="number">2</span>));</span><br><span class="line">numberRangeSet.add(Range.closed(<span class="number">3</span>, <span class="number">5</span>));</span><br><span class="line">numberRangeSet.add(Range.closed(<span class="number">6</span>, <span class="number">8</span>));</span><br><span class="line">RangeSet<Integer> numberRangeComplementSet = numberRangeSet.complement();</span><br><span class="line"></span><br><span class="line">System.out.println(numberRangeSet); <span class="comment">// [[0..2], [3..5], [6..8]]</span></span><br><span class="line">System.out.println(numberRangeComplementSet); <span class="comment">// [(-∞..0), (2..3), (5..6), (8..+∞)]</span></span><br></pre></td></tr></table></figure><p></p><p>判断一个RangeSet是否和另一个范围有交集:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">RangeSet<Integer> numberRangeSet = TreeRangeSet.create();</span><br><span class="line"></span><br><span class="line">numberRangeSet.add(Range.closed(<span class="number">0</span>, <span class="number">2</span>));</span><br><span class="line">numberRangeSet.add(Range.closed(<span class="number">3</span>, <span class="number">10</span>));</span><br><span class="line">numberRangeSet.add(Range.closed(<span class="number">15</span>, <span class="number">18</span>));</span><br><span class="line"></span><br><span class="line">System.out.println(numberRangeSet); <span class="comment">// [[0..2], [3..10], [15..18]]</span></span><br><span class="line">System.out.println(numberRangeSet.intersects(Range.closed(<span class="number">4</span>, <span class="number">17</span>))); <span class="comment">// true</span></span><br></pre></td></tr></table></figure><p></p><p>遍历RangeSet的范围区间:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">RangeSet<Integer> numberRangeSet = TreeRangeSet.create();</span><br><span class="line"></span><br><span class="line">numberRangeSet.add(Range.closed(<span class="number">0</span>, <span class="number">2</span>));</span><br><span class="line">numberRangeSet.add(Range.closed(<span class="number">3</span>, <span class="number">10</span>));</span><br><span class="line">numberRangeSet.add(Range.closed(<span class="number">15</span>, <span class="number">18</span>));</span><br><span class="line"></span><br><span class="line">Set<Range<Integer>> ranges = numberRangeSet.asRanges();</span><br><span class="line">ranges.forEach(System.out::print); <span class="comment">// [0..2][3..10][15..18]</span></span><br></pre></td></tr></table></figure><p></p><p>从RangeSet中获取包含某个值的访问区间:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">RangeSet<Integer> numberRangeSet = TreeRangeSet.create();</span><br><span class="line"></span><br><span class="line">numberRangeSet.add(Range.closed(<span class="number">0</span>, <span class="number">2</span>));</span><br><span class="line">numberRangeSet.add(Range.closed(<span class="number">3</span>, <span class="number">10</span>));</span><br><span class="line">numberRangeSet.add(Range.closed(<span class="number">15</span>, <span class="number">18</span>));</span><br><span class="line"></span><br><span class="line">System.out.println(numberRangeSet.rangeContaining(<span class="number">7</span>)); <span class="comment">// [3..10]</span></span><br></pre></td></tr></table></figure><p></p><h3 id="RangeMap"><a href="#RangeMap" class="headerlink" title="RangeMap"></a>RangeMap</h3><p>RangeMap是一组不相连的、非空的区间与指定值的映射,基本实现为TreeRangeMap光这样说有点抽象,看些例子:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">RangeMap<Integer, String> rangeMap = TreeRangeMap.create();</span><br><span class="line">rangeMap.put(Range.closed(<span class="number">1</span>, <span class="number">10</span>), <span class="string">"foo"</span>);</span><br><span class="line">System.out.println(rangeMap); <span class="comment">// [[1..10]=foo]</span></span><br><span class="line"></span><br><span class="line">rangeMap.put(Range.open(<span class="number">3</span>, <span class="number">6</span>), <span class="string">"bar"</span>);</span><br><span class="line">System.out.println(rangeMap); <span class="comment">// [[1..3]=foo, (3..6)=bar, [6..10]=foo]</span></span><br><span class="line"></span><br><span class="line">rangeMap.put(Range.open(<span class="number">10</span>, <span class="number">20</span>), <span class="string">"eoo"</span>);</span><br><span class="line">System.out.println(rangeMap); <span class="comment">// [[1..3]=foo, (3..6)=bar, [6..10]=foo, (10..20)=eoo]</span></span><br><span class="line"></span><br><span class="line">rangeMap.remove(Range.closed(<span class="number">5</span>, <span class="number">11</span>));</span><br><span class="line">System.out.println(rangeMap); <span class="comment">// [[1..3]=foo, (3..5)=bar, (11..20)=eoo]</span></span><br></pre></td></tr></table></figure><p></p><p>从RangeMap中获取一个Entry:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">RangeMap<Integer, String> rangeMap = TreeRangeMap.create();</span><br><span class="line"></span><br><span class="line">rangeMap.put(Range.closed(<span class="number">0</span>, <span class="number">2</span>), <span class="string">"foo"</span>);</span><br><span class="line">rangeMap.put(Range.closed(<span class="number">3</span>, <span class="number">5</span>), <span class="string">"bar"</span>);</span><br><span class="line">rangeMap.put(Range.closed(<span class="number">6</span>, <span class="number">8</span>), <span class="string">"eoo"</span>);</span><br><span class="line">Map.Entry<Range<Integer>, String> entry = rangeMap.getEntry(<span class="number">7</span>);</span><br><span class="line"></span><br><span class="line">System.out.println(entry.getKey()); <span class="comment">// [6..8]</span></span><br><span class="line">System.out.println(entry.getValue()); <span class="comment">// eoo</span></span><br></pre></td></tr></table></figure><p></p><p>剩下的操作和RangeSet差不多。</p><h3 id="BiMap"><a href="#BiMap" class="headerlink" title="BiMap"></a>BiMap</h3><p>BiMap是一种特殊的,双向映射的Map,可以确保不会出现重复的值并且我们总是可以安全地通过key获取到value。BiMap的基本实现为HashBiMap。</p><p>看看例子:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">BiMap<String, String> biMap = HashBiMap.create();</span><br><span class="line">biMap.put(<span class="string">"k1"</span>, <span class="string">"v1"</span>);</span><br><span class="line">biMap.put(<span class="string">"k2"</span>, <span class="string">"v2"</span>);</span><br><span class="line">biMap.put(<span class="string">"k3"</span>, <span class="string">"v3"</span>);</span><br><span class="line">System.out.println(biMap); <span class="comment">// {k1=v1, k2=v2, k3=v3}</span></span><br><span class="line"></span><br><span class="line">BiMap<String, String> inverse = biMap.inverse();</span><br><span class="line">System.out.println(inverse); <span class="comment">// {v1=k1, v2=k2, v3=k3}</span></span><br></pre></td></tr></table></figure><p></p><p>通过<code>inverse</code>可以得到值,键映射的BiMap。</p><p>往BiMap里添加重复的值将会报错:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">BiMap<String, String> biMap = HashBiMap.create();</span><br><span class="line">biMap.put(<span class="string">"k1"</span>, <span class="string">"v1"</span>);</span><br><span class="line">biMap.put(<span class="string">"k2"</span>, <span class="string">"v2"</span>);</span><br><span class="line">biMap.put(<span class="string">"k3"</span>, <span class="string">"v1"</span>);</span><br></pre></td></tr></table></figure><p><img src="img/QQ截图20190422172835.png" alt="QQ截图20190422172835.png"></p><p>如果非要添加重复的值的话,可以用<code>forcePut</code>方法:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">BiMap<String, String> biMap = HashBiMap.create();</span><br><span class="line">biMap.put(<span class="string">"k1"</span>, <span class="string">"v1"</span>);</span><br><span class="line">biMap.put(<span class="string">"k2"</span>, <span class="string">"v2"</span>);</span><br><span class="line">biMap.forcePut(<span class="string">"k3"</span>, <span class="string">"v1"</span>);</span><br><span class="line">System.out.println(biMap); <span class="comment">// {k2=v2, k3=v1}</span></span><br></pre></td></tr></table></figure><p></p><h3 id="Table"><a href="#Table" class="headerlink" title="Table"></a>Table</h3><p>Table是一个包含行,列和单元格的集合类型,行和列组成有序键对。</p><p>创建一个HashBasedTable(内部使用LinkedHashMap):</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Table<String, String, Integer> hashBasedTable = HashBasedTable.create();</span><br></pre></td></tr></table></figure><p></p><p>如果需要对table的行和列按照自然顺序或者提供的排序规则进行排序的话,可以创建一个TreeBasedTable:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Table<String, String, Integer> treeBasedTable = TreeBasedTable.create();</span><br></pre></td></tr></table></figure><p></p><p>如果事先知道行和列的值,并且table大小是固定的话,可以使用ArrayTable:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">List<String> row = Lists.newArrayList(<span class="string">"r1"</span>, <span class="string">"r2"</span>);</span><br><span class="line">List<String> column = Lists.newArrayList(<span class="string">"c1"</span>, <span class="string">"c2"</span>, <span class="string">"c3"</span>);</span><br><span class="line">Table<String, String, Integer> arrayTable = ArrayTable.create(row, column);</span><br><span class="line">System.out.println(arrayTable); <span class="comment">// {r1={c1=null, c2=null, c3=null}, r2={c1=null, c2=null, c3=null}}</span></span><br></pre></td></tr></table></figure><p></p><p>上面例子创建了一个两行三列的table。</p><p>创建不可变table:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Table<String, String, String> immutableTable = ImmutableTable.<String, String, String> builder()</span><br><span class="line"> .put(<span class="string">"r1"</span>, <span class="string">"c1"</span>, <span class="string">"hello"</span>)</span><br><span class="line"> .build();</span><br></pre></td></tr></table></figure><p></p><p>通过行和列获取单元格的值:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">Table<String, String, String> hashBasedTable = HashBasedTable.create();</span><br><span class="line">hashBasedTable.put(<span class="string">"r1"</span>, <span class="string">"c1"</span>, <span class="string">"hello"</span>);</span><br><span class="line">hashBasedTable.put(<span class="string">"r1"</span>, <span class="string">"c2"</span>, <span class="string">"world"</span>);</span><br><span class="line">hashBasedTable.put(<span class="string">"r2"</span>, <span class="string">"c1"</span>, <span class="string">"good"</span>);</span><br><span class="line">hashBasedTable.put(<span class="string">"r2"</span>, <span class="string">"c2"</span>, <span class="string">"bye"</span>);</span><br><span class="line"></span><br><span class="line">System.out.println(hashBasedTable); <span class="comment">// {r1={c1=hello, c2=world}, r2={c1=good, c2=bye}}</span></span><br><span class="line"></span><br><span class="line">String v1 = hashBasedTable.get(<span class="string">"r1"</span>, <span class="string">"c1"</span>);</span><br><span class="line">String v2 = hashBasedTable.get(<span class="string">"r2"</span>, <span class="string">"c3"</span>);</span><br><span class="line"></span><br><span class="line">System.out.println(v1); <span class="comment">// hello</span></span><br><span class="line">System.out.println(v2); <span class="comment">// null</span></span><br></pre></td></tr></table></figure><p></p><p>我们可以检测table是否包含某个行键,某个列键,某个值和某个行和列组合的键:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">Table<String, String, String> hashBasedTable = HashBasedTable.create();</span><br><span class="line">hashBasedTable.put(<span class="string">"r1"</span>, <span class="string">"c1"</span>, <span class="string">"hello"</span>);</span><br><span class="line">hashBasedTable.put(<span class="string">"r1"</span>, <span class="string">"c2"</span>, <span class="string">"world"</span>);</span><br><span class="line">hashBasedTable.put(<span class="string">"r2"</span>, <span class="string">"c1"</span>, <span class="string">"good"</span>);</span><br><span class="line">hashBasedTable.put(<span class="string">"r2"</span>, <span class="string">"c2"</span>, <span class="string">"bye"</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">boolean</span> b1 = hashBasedTable.contains(<span class="string">"r1"</span>, <span class="string">"c2"</span>); <span class="comment">// true</span></span><br><span class="line"><span class="keyword">boolean</span> b2 = hashBasedTable.containsColumn(<span class="string">"c3"</span>); <span class="comment">// false</span></span><br><span class="line"><span class="keyword">boolean</span> b3 = hashBasedTable.containsRow(<span class="string">"r2"</span>); <span class="comment">// true</span></span><br><span class="line"><span class="keyword">boolean</span> b4 = hashBasedTable.containsValue(<span class="string">"world"</span>); <span class="comment">// true</span></span><br></pre></td></tr></table></figure><p></p><p>通过行和列删除单元格,返回被删除的值:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">Table<String, String, String> hashBasedTable = HashBasedTable.create();</span><br><span class="line">hashBasedTable.put(<span class="string">"r1"</span>, <span class="string">"c1"</span>, <span class="string">"hello"</span>);</span><br><span class="line">hashBasedTable.put(<span class="string">"r1"</span>, <span class="string">"c2"</span>, <span class="string">"world"</span>);</span><br><span class="line">hashBasedTable.put(<span class="string">"r2"</span>, <span class="string">"c1"</span>, <span class="string">"good"</span>);</span><br><span class="line">hashBasedTable.put(<span class="string">"r2"</span>, <span class="string">"c2"</span>, <span class="string">"bye"</span>);</span><br><span class="line"></span><br><span class="line">String removeValue = hashBasedTable.remove(<span class="string">"r1"</span>, <span class="string">"c1"</span>);</span><br><span class="line"></span><br><span class="line">System.out.println(removeValue); <span class="comment">// hello</span></span><br><span class="line">System.out.println(hashBasedTable); <span class="comment">// {r1={c2=world}, r2={c1=good, c2=bye}}</span></span><br></pre></td></tr></table></figure><p></p><p>我们可以通过行或列得到一个Map,如果通过行得到Map,那么Map的键为列值,Map的值为对应单元格的值,光说有点抽象,看个例子:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">Table<String, String, String> hashBasedTable = HashBasedTable.create();</span><br><span class="line">hashBasedTable.put(<span class="string">"r1"</span>, <span class="string">"c1"</span>, <span class="string">"hello"</span>);</span><br><span class="line">hashBasedTable.put(<span class="string">"r1"</span>, <span class="string">"c2"</span>, <span class="string">"world"</span>);</span><br><span class="line">hashBasedTable.put(<span class="string">"r2"</span>, <span class="string">"c1"</span>, <span class="string">"good"</span>);</span><br><span class="line">hashBasedTable.put(<span class="string">"r2"</span>, <span class="string">"c2"</span>, <span class="string">"bye"</span>);</span><br><span class="line"></span><br><span class="line">Map<String, String> c2Map = hashBasedTable.column(<span class="string">"c2"</span>);</span><br><span class="line">Map<String, String> r1Map = hashBasedTable.row(<span class="string">"r1"</span>);</span><br><span class="line"></span><br><span class="line">System.out.println(c2Map); <span class="comment">// {r1=world, r2=bye}</span></span><br><span class="line">System.out.println(r1Map); <span class="comment">// {c1=hello, c2=world}</span></span><br><span class="line">System.out.println(c2Map.get(<span class="string">"r1"</span>)); <span class="comment">// world</span></span><br></pre></td></tr></table></figure><p></p><p>我们还可以单独获取所有行或者所有列组成的Map:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">Table<String, String, String> hashBasedTable = HashBasedTable.create();</span><br><span class="line">hashBasedTable.put(<span class="string">"r1"</span>, <span class="string">"c1"</span>, <span class="string">"hello"</span>);</span><br><span class="line">hashBasedTable.put(<span class="string">"r1"</span>, <span class="string">"c2"</span>, <span class="string">"world"</span>);</span><br><span class="line">hashBasedTable.put(<span class="string">"r2"</span>, <span class="string">"c1"</span>, <span class="string">"good"</span>);</span><br><span class="line">hashBasedTable.put(<span class="string">"r2"</span>, <span class="string">"c2"</span>, <span class="string">"bye"</span>);</span><br><span class="line"></span><br><span class="line">Map<String, Map<String, String>> columnMap = hashBasedTable.columnMap();</span><br><span class="line">Map<String, Map<String, String>> rowMap = hashBasedTable.rowMap();</span><br><span class="line"></span><br><span class="line">System.out.println(columnMap); <span class="comment">// {c1={r1=hello, r2=good}, c2={r1=world, r2=bye}}</span></span><br><span class="line">System.out.println(rowMap); <span class="comment">// {r1={c1=hello, c2=world}, r2={c1=good, c2=bye}}</span></span><br></pre></td></tr></table></figure><p></p><p>获取所有行键、列键或者值的集合:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">Table<String, String, String> hashBasedTable = HashBasedTable.create();</span><br><span class="line">hashBasedTable.put(<span class="string">"r1"</span>, <span class="string">"c1"</span>, <span class="string">"hello"</span>);</span><br><span class="line">hashBasedTable.put(<span class="string">"r1"</span>, <span class="string">"c2"</span>, <span class="string">"world"</span>);</span><br><span class="line">hashBasedTable.put(<span class="string">"r2"</span>, <span class="string">"c1"</span>, <span class="string">"good"</span>);</span><br><span class="line">hashBasedTable.put(<span class="string">"r2"</span>, <span class="string">"c2"</span>, <span class="string">"bye"</span>);</span><br><span class="line"></span><br><span class="line">Set<String> rowKeySet = hashBasedTable.rowKeySet();</span><br><span class="line">Set<String> columnKeySet = hashBasedTable.columnKeySet();</span><br><span class="line">Set<Table.Cell<String, String, String>> cells = hashBasedTable.cellSet();</span><br><span class="line"></span><br><span class="line">System.out.println(rowKeySet); <span class="comment">// [r1, r2]</span></span><br><span class="line">System.out.println(columnKeySet); <span class="comment">// [c1, c2]</span></span><br><span class="line">System.out.println(cells); <span class="comment">// [(r1,c1)=hello, (r1,c2)=world, (r2,c1)=good, (r2,c2)=bye]</span></span><br></pre></td></tr></table></figure><p></p><h3 id="Multiset"><a href="#Multiset" class="headerlink" title="Multiset"></a>Multiset</h3><p>Multiset和java.util.set类似,不过Mutiset可以添加重复的值:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">HashMultiset<String> hashMultiset = HashMultiset.create();</span><br><span class="line">hashMultiset.add(<span class="string">"are you ok?"</span>);</span><br><span class="line">hashMultiset.add(<span class="string">"are you ok?"</span>);</span><br><span class="line">hashMultiset.add(<span class="string">"are you ok?"</span>);</span><br><span class="line"></span><br><span class="line">System.out.println(hashMultiset); <span class="comment">// [are you ok? x 3]</span></span><br><span class="line"></span><br><span class="line">hashMultiset.remove(<span class="string">"are you ok?"</span>);</span><br><span class="line">System.out.println(hashMultiset); <span class="comment">// [are you ok? x 2]</span></span><br><span class="line"></span><br><span class="line">hashMultiset.setCount(<span class="string">"are you ok?"</span>, <span class="number">10</span>); <span class="comment">// 直接设置元素个数</span></span><br><span class="line">System.out.println(hashMultiset); <span class="comment">// [are you ok? x 10]</span></span><br></pre></td></tr></table></figure><p></p><p>在并发环境下,我们可以使用ConcurrentHashMultiset,它的add和remove方法是线程安全的。唯一值得注意的是,在并发环境下使用setCount方法时候,需使用下面这种方式:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">HashMultiset<String> hashMultiset = HashMultiset.create();</span><br><span class="line">hashMultiset.setCount(<span class="string">"are you ok?"</span>, <span class="number">0</span>, <span class="number">5</span>);</span><br><span class="line">hashMultiset.setCount(<span class="string">"are you ok?"</span>, <span class="number">10</span>, <span class="number">5</span>);</span><br><span class="line"></span><br><span class="line">System.out.println(hashMultiset); <span class="comment">// [are you ok? x 5]</span></span><br></pre></td></tr></table></figure><p></p><p>第一个参数为需要添加的值,第二个参数为当前Multiset里元素个数,第三个参数为需要添加的元素个数。只有第二个参数的值正确的时候,setCount才有效,所以<code>hashMultiset.setCount("are you ok?", 10, 5)</code>实际上是不生效的。</p><h3 id="Multimap"><a href="#Multimap" class="headerlink" title="Multimap"></a>Multimap</h3><p>Multimap可以通过一个键映射多个值:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">String key = <span class="string">"hello"</span>;</span><br><span class="line">ArrayListMultimap<String, String> multimap = ArrayListMultimap.create();</span><br><span class="line">multimap.put(key, <span class="string">"world"</span>);</span><br><span class="line">multimap.put(key, <span class="string">"java"</span>);</span><br><span class="line"></span><br><span class="line">System.out.println(multimap); <span class="comment">// {hello=[world, java]}</span></span><br><span class="line">System.out.println(multimap.get(key)); <span class="comment">// [world, java]</span></span><br></pre></td></tr></table></figure><p></p><h3 id="ClassToInstanceMap"><a href="#ClassToInstanceMap" class="headerlink" title="ClassToInstanceMap"></a>ClassToInstanceMap</h3><p>使用类型作为键:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">MutableClassToInstanceMap<Object> classToInstanceMap = MutableClassToInstanceMap.create();</span><br><span class="line">classToInstanceMap.put(String.class, <span class="string">"hello"</span>);</span><br><span class="line">classToInstanceMap.put(Integer.class, <span class="number">777</span>);</span><br><span class="line">classToInstanceMap.put(Double.class, <span class="number">43.96</span>);</span><br><span class="line"></span><br><span class="line">System.out.println(classToInstanceMap); <span class="comment">// {class java.lang.Double=43.96, class java.lang.String=hello, class java.lang.Integer=777}</span></span><br><span class="line">System.out.println(classToInstanceMap.get(Double.class)); <span class="comment">// 43.96</span></span><br></pre></td></tr></table></figure><p></p><h2 id="Lists、Maps-amp-Sets"><a href="#Lists、Maps-amp-Sets" class="headerlink" title="Lists、Maps&Sets"></a>Lists、Maps&Sets</h2><h3 id="Lists"><a href="#Lists" class="headerlink" title="Lists"></a>Lists</h3><p>创建一个List:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ArrayList<String> list = Lists.newArrayList(<span class="string">"a"</span>, <span class="string">"b"</span>, <span class="string">"c"</span>);</span><br></pre></td></tr></table></figure><p></p><p>反转List:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">ArrayList<String> list = Lists.newArrayList(<span class="string">"a"</span>, <span class="string">"b"</span>, <span class="string">"c"</span>);</span><br><span class="line"></span><br><span class="line">List<String> reverse = Lists.reverse(list);</span><br><span class="line">System.out.println(reverse); <span class="comment">// [c, b, a]</span></span><br></pre></td></tr></table></figure><p></p><p>通过字符串生成字符集合:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">List<Character> characters = Lists.charactersOf(<span class="string">"mrbird"</span>);</span><br><span class="line">System.out.println(characters); <span class="comment">// [m, r, b, i, r, d]</span></span><br></pre></td></tr></table></figure><p></p><p>将集合按照指定区块大小分区:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">List<String> list = Lists.newArrayList(<span class="string">"java"</span>, <span class="string">"php"</span>, <span class="string">"go"</span>, <span class="string">"python"</span>, <span class="string">"c#"</span>, <span class="string">"javascript"</span>);</span><br><span class="line">List<List<String>> partition = Lists.partition(list, <span class="number">2</span>);</span><br><span class="line"></span><br><span class="line">System.out.println(partition); <span class="comment">// [[java, php], [go, python], [c#, javascript]]</span></span><br></pre></td></tr></table></figure><p></p><p>一个删除List中重复项的技巧:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">List<String> list = Lists.newArrayList(<span class="string">"a"</span>, <span class="string">"p"</span>, <span class="string">"p"</span>, <span class="string">"l"</span>, <span class="string">"e"</span>);</span><br><span class="line"></span><br><span class="line">ImmutableList<String> newList = ImmutableSet.copyOf(list).asList();</span><br><span class="line">System.out.println(newList); <span class="comment">// [a, p, l, e]</span></span><br></pre></td></tr></table></figure><p></p><p>从集合中删除null值:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">List<String> list = Lists.newArrayList(<span class="string">"java"</span>, <span class="keyword">null</span>,<span class="string">" python"</span>);</span><br><span class="line"></span><br><span class="line">Iterables.removeIf(list, Objects::isNull);</span><br><span class="line">System.out.println(list); <span class="comment">// [java, python]</span></span><br></pre></td></tr></table></figure><p></p><h3 id="Sets"><a href="#Sets" class="headerlink" title="Sets"></a>Sets</h3><p>通过Sets创建set:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Set<Object> hashSet = Sets.newHashSet();</span><br></pre></td></tr></table></figure><p></p><p>合并两个Set:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Set<String> set1 = ImmutableSet.of(<span class="string">"a"</span>, <span class="string">"b"</span>, <span class="string">"c"</span>);</span><br><span class="line">Set<String> set2 = ImmutableSet.of(<span class="string">"b"</span>, <span class="string">"c"</span>, <span class="string">"d"</span>);</span><br><span class="line"></span><br><span class="line">Set<String> union = Sets.union(set1, set2);</span><br><span class="line">System.out.println(union); <span class="comment">// [a, b, c, d]</span></span><br></pre></td></tr></table></figure><p></p><p>可以通过<code>Sets.cartesianProduct()</code>获取两个Set的笛卡尔积:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Set<Character> first = ImmutableSet.of(<span class="string">'a'</span>, <span class="string">'b'</span>);</span><br><span class="line">Set<Character> second = ImmutableSet.of(<span class="string">'c'</span>, <span class="string">'d'</span>);</span><br><span class="line">Set<List<Character>> result = Sets.cartesianProduct(first, second);</span><br><span class="line"></span><br><span class="line">System.out.println(result); <span class="comment">// [[a, c], [a, d], [b, c], [b, d]]</span></span><br></pre></td></tr></table></figure><p></p><p>获取两个Set的交集:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Set<Character> first = ImmutableSet.of(<span class="string">'a'</span>, <span class="string">'b'</span>, <span class="string">'c'</span>);</span><br><span class="line">Set<Character> second = ImmutableSet.of(<span class="string">'c'</span>, <span class="string">'d'</span>, <span class="string">'e'</span>);</span><br><span class="line">Set<Character> intersection = Sets.intersection(first, second);</span><br><span class="line"></span><br><span class="line">System.out.println(intersection); <span class="comment">// [c]</span></span><br></pre></td></tr></table></figure><p></p><p>获取两个Set的差集:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Set<Character> first = ImmutableSet.of(<span class="string">'a'</span>, <span class="string">'b'</span>, <span class="string">'c'</span>);</span><br><span class="line">Set<Character> second = ImmutableSet.of(<span class="string">'c'</span>, <span class="string">'d'</span>, <span class="string">'e'</span>);</span><br><span class="line">Set<Character> difference = Sets.symmetricDifference(first, second);</span><br><span class="line"></span><br><span class="line">System.out.println(difference); <span class="comment">// [a, b, d, e]</span></span><br></pre></td></tr></table></figure><p></p><h3 id="Maps"><a href="#Maps" class="headerlink" title="Maps"></a>Maps</h3><p>通过Maps创建Map:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">HashMap<Object, Object> map = Maps.newHashMap();</span><br></pre></td></tr></table></figure><p></p><p>创建期望大小的Map:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">HashMap<Object, Object> map = Maps.newHashMapWithExpectedSize(<span class="number">5</span>);</span><br></pre></td></tr></table></figure><p></p><h2 id="Joiner与Splitter"><a href="#Joiner与Splitter" class="headerlink" title="Joiner与Splitter"></a>Joiner与Splitter</h2><h3 id="Joiner"><a href="#Joiner" class="headerlink" title="Joiner"></a>Joiner</h3><p>Joiner用于连接操作。比如将List里的元素通过“,”连接成一个字符串:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">List<String> list = Lists.newArrayList(<span class="string">"a"</span>, <span class="string">"b"</span>, <span class="string">"c"</span>);</span><br><span class="line">String join = Joiner.on(<span class="string">","</span>).join(list);</span><br><span class="line"></span><br><span class="line">System.out.println(join); <span class="comment">// a,b,c</span></span><br></pre></td></tr></table></figure><p></p><p>使用Joiner将Map转换为String:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">HashMap<String, Integer> map = Maps.newHashMap();</span><br><span class="line">map.put(<span class="string">"mrbird"</span>, <span class="number">18</span>);</span><br><span class="line">map.put(<span class="string">"scott"</span>, <span class="number">28</span>);</span><br><span class="line"></span><br><span class="line">String join = Joiner.on(<span class="string">","</span>).withKeyValueSeparator(<span class="string">"~"</span>).join(map);</span><br><span class="line">System.out.println(join); <span class="comment">// mrbird~18,scott~28</span></span><br></pre></td></tr></table></figure><p></p><p>在使用Joiner的时候,如果集合中含有null值,我们可以选择跳过它:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">List<String> list = Lists.newArrayList(<span class="string">"a"</span>, <span class="keyword">null</span>, <span class="string">"b"</span>, <span class="string">"c"</span>, <span class="string">"d"</span>);</span><br><span class="line">String result = Joiner.on(<span class="string">","</span>).skipNulls().join(list);</span><br><span class="line"></span><br><span class="line">System.out.println(result); <span class="comment">// a,b,c,d</span></span><br></pre></td></tr></table></figure><p></p><p>或者使用指定值替代null:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">List<String> list = Lists.newArrayList(<span class="string">"a"</span>, <span class="keyword">null</span>, <span class="string">"b"</span>, <span class="string">"c"</span>, <span class="string">"d"</span>);</span><br><span class="line">String result = Joiner.on(<span class="string">","</span>).useForNull(<span class="string">"空"</span>).join(list);</span><br><span class="line"></span><br><span class="line">System.out.println(result); <span class="comment">// a,空,b,c,d</span></span><br></pre></td></tr></table></figure><p></p><h3 id="Splitter"><a href="#Splitter" class="headerlink" title="Splitter"></a>Splitter</h3><p>Splitter用于将String拆分为集合类型,看个例子:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">String value = <span class="string">"a,b,c,d "</span>;</span><br><span class="line">List<String> list = Splitter.on(<span class="string">","</span>).trimResults().splitToList(value);</span><br><span class="line"></span><br><span class="line">System.out.println(list); <span class="comment">// [a, b, c, d]</span></span><br></pre></td></tr></table></figure><p></p><p>使用Splitter将String拆分为Map:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"> String value = <span class="string">"mrbird=18,scott=28"</span>;</span><br><span class="line">Map<String, String> map = Splitter.on(<span class="string">","</span>).withKeyValueSeparator(<span class="string">"="</span>).split(value);</span><br><span class="line"></span><br><span class="line">System.out.println(map); <span class="comment">// {mrbird=18, scott=28}</span></span><br></pre></td></tr></table></figure><p></p><p>分割具有多种分隔符的String:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">String value = <span class="string">"a.b,,c,,.."</span>;</span><br><span class="line">List<String> result = Splitter.onPattern(<span class="string">"[.,]"</span>).omitEmptyStrings().splitToList(value);</span><br><span class="line"></span><br><span class="line">System.out.println(result); <span class="comment">// [a, b, c]</span></span><br></pre></td></tr></table></figure><p></p><p><code>omitEmptyStrings</code>用于忽略空字符串。</p><p>我们还可以通过指定长度来拆分字符串:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">String value = <span class="string">"人们都说:“桂林山水甲天下”,我们乘着木船荡漾在漓江上,来观赏桂林的山水。"</span>;</span><br><span class="line"></span><br><span class="line">List<String> list = Splitter.fixedLength(<span class="number">3</span>).splitToList(value);</span><br><span class="line">System.out.println(list); <span class="comment">// [人们都, 说:“, 桂林山, 水甲天, 下”,, 我们乘, 着木船, 荡漾在, 漓江上, ,来观, 赏桂林, 的山水, 。]</span></span><br></pre></td></tr></table></figure><p></p><p>也可以指定拆分项的长度:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">String value = <span class="string">"a-b-c-d-e"</span>;</span><br><span class="line">List<String> result = Splitter.on(<span class="string">"-"</span>).limit(<span class="number">4</span>).splitToList(value);</span><br><span class="line"></span><br><span class="line">System.out.println(result); <span class="comment">// [a, b, c, d-e]</span></span><br></pre></td></tr></table></figure><p></p><p>可以看到d-e没有被拆分。</p><h2 id="Filter-amp-Transform"><a href="#Filter-amp-Transform" class="headerlink" title="Filter&Transform"></a>Filter&Transform</h2><h3 id="Filter"><a href="#Filter" class="headerlink" title="Filter"></a>Filter</h3><p>可以通过Guava提供的Predicates来实现各种集合过滤操作。</p><p>比如找出集合中包含a的元素:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">List<String> list = Lists.newArrayList(<span class="string">"java"</span>, <span class="string">"javascript"</span>, <span class="string">"c#"</span>, <span class="string">"golang"</span>);</span><br><span class="line">Iterable<String> result = Iterables.filter(list, Predicates.containsPattern(<span class="string">"a"</span>));</span><br><span class="line"></span><br><span class="line">System.out.println(result); <span class="comment">// [java, javascript, golang]</span></span><br></pre></td></tr></table></figure><p></p><p>上面的例子也可以通过<code>Collections2.filter</code>来实现:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">List<String> list = Lists.newArrayList(<span class="string">"java"</span>, <span class="string">"javascript"</span>, <span class="string">"c#"</span>, <span class="string">"golang"</span>);</span><br><span class="line">Collection<String> result = Collections2.filter(list, Predicates.containsPattern(<span class="string">"a"</span>));</span><br><span class="line"></span><br><span class="line">System.out.println(result);</span><br></pre></td></tr></table></figure><p></p><p>我们也可以编写自定义的过滤规则:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"> Predicate<String> predicate = <span class="keyword">new</span> Predicate<String>() {</span><br><span class="line"> <span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">apply</span><span class="params">(@Nullable String input)</span> </span>{</span><br><span class="line"> <span class="keyword">return</span> input.endsWith(<span class="string">"a"</span>) || input.contains(<span class="string">"#"</span>);</span><br><span class="line"> }</span><br><span class="line"> <span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">test</span><span class="params">(String input)</span> </span>{</span><br><span class="line"> <span class="keyword">return</span> <span class="keyword">this</span>.apply(input);</span><br><span class="line"> }</span><br><span class="line">};</span><br><span class="line">List<String> list = Lists.newArrayList(<span class="string">"java"</span>, <span class="string">"javascript"</span>, <span class="string">"c#"</span>, <span class="string">"golang"</span>);</span><br><span class="line">Collection<String> result = Collections2.filter(list, predicate);</span><br><span class="line"></span><br><span class="line">System.out.println(result); <span class="comment">// [java, c#]</span></span><br></pre></td></tr></table></figure><p></p><p>组合多个过滤条件:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">List<String> list = Lists.newArrayList(<span class="string">"java"</span>, <span class="string">"javascript"</span>, <span class="string">"c#"</span>, <span class="string">"golang"</span>);</span><br><span class="line">Collection<String> result = Collections2.filter(list,</span><br><span class="line"> Predicates.or(</span><br><span class="line"> Predicates.containsPattern(<span class="string">"a"</span>),</span><br><span class="line"> Predicates.containsPattern(<span class="string">"#"</span>)</span><br><span class="line"> ));</span><br><span class="line">System.out.println(result); <span class="comment">// [java, javascript, c#, golang]</span></span><br></pre></td></tr></table></figure><p></p><p>过滤掉集合中的null:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">List<String> list = Lists.newArrayList(<span class="string">"java"</span>, <span class="keyword">null</span>,<span class="string">" python"</span>);</span><br><span class="line">Collection<String> result = Collections2.filter(list, Predicates.<String>notNull());</span><br><span class="line"></span><br><span class="line">System.out.println(result); <span class="comment">// [java, python]</span></span><br></pre></td></tr></table></figure><p></p><p>检测集合中是否有包含a字符的元素:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">List<String> list = Lists.newArrayList(<span class="string">"java"</span>, <span class="string">"c#"</span>,<span class="string">" python"</span>);</span><br><span class="line"><span class="keyword">boolean</span> result = Iterables.any(list, Predicates.containsPattern(<span class="string">"a"</span>));</span><br><span class="line"></span><br><span class="line">System.out.println(result); <span class="comment">// true</span></span><br></pre></td></tr></table></figure><p></p><h3 id="Transform"><a href="#Transform" class="headerlink" title="Transform"></a>Transform</h3><p>将集合转换为元素长度的集合:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">Function<String, Integer> function = <span class="keyword">new</span> Function<String, Integer>() {</span><br><span class="line"> <span class="meta">@Nullable</span></span><br><span class="line"> <span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> Integer <span class="title">apply</span><span class="params">(@Nullable String s)</span> </span>{</span><br><span class="line"> <span class="keyword">return</span> s.length();</span><br><span class="line"> }</span><br><span class="line">};</span><br><span class="line">List<String> list = Lists.newArrayList(<span class="string">"java"</span>, <span class="string">"c#"</span>, <span class="string">" python"</span>);</span><br><span class="line">Iterable<Integer> result = Iterables.transform(list, function);</span><br><span class="line"></span><br><span class="line">System.out.println(result); <span class="comment">// [4, 2, 7]</span></span><br></pre></td></tr></table></figure><p></p><p>上面的例子同样可以使用<code>Collections2.transform</code>来代替<code>Iterables.transform</code>。</p><p>我们也可以通过<code>Functions.forPredicate</code>来创建简单的转换函数Function:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">List<String> list = Lists.newArrayList(<span class="string">"java"</span>, <span class="string">"c#"</span>, <span class="string">" python"</span>);</span><br><span class="line">Iterable<Boolean> result = Iterables.transform(list, Functions.forPredicate(Predicates.containsPattern(<span class="string">"#"</span>)));</span><br><span class="line"></span><br><span class="line">System.out.println(result); <span class="comment">// [false, true, false]</span></span><br></pre></td></tr></table></figure><p></p><p>组合多个转换函数:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">Function<String, String> f1 = <span class="keyword">new</span> Function<String, String>() {</span><br><span class="line"> <span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> String <span class="title">apply</span><span class="params">(String input)</span> </span>{</span><br><span class="line"> <span class="keyword">return</span> <span class="string">"i like "</span> + input;</span><br><span class="line"> }</span><br><span class="line">};</span><br><span class="line"></span><br><span class="line">Function<String, String> f2 = <span class="keyword">new</span> Function<String, String>() {</span><br><span class="line"> <span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> String <span class="title">apply</span><span class="params">(String input)</span> </span>{</span><br><span class="line"> <span class="keyword">return</span> input.toUpperCase();</span><br><span class="line"> }</span><br><span class="line">};</span><br><span class="line">List<String> list = Lists.newArrayList(<span class="string">"java"</span>, <span class="string">"c#"</span>, <span class="string">" python"</span>);</span><br><span class="line">Iterable<String> result = Iterables.transform(list, Functions.compose(f2, f1));</span><br><span class="line"></span><br><span class="line">System.out.println(result); <span class="comment">// [I LIKE JAVA, I LIKE C#, I LIKE PYTHON]</span></span><br></pre></td></tr></table></figure><p></p><p>我们也可以将过滤和转换组合在一起使用:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">Predicate<String> predicate = <span class="keyword">new</span> Predicate<String>() {</span><br><span class="line"> <span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">apply</span><span class="params">(String input)</span> </span>{</span><br><span class="line"> <span class="keyword">return</span> input.startsWith(<span class="string">"j"</span>);</span><br><span class="line"> }</span><br><span class="line"> <span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">test</span><span class="params">(String input)</span> </span>{</span><br><span class="line"> <span class="keyword">return</span> <span class="keyword">this</span>.apply(input);</span><br><span class="line"> }</span><br><span class="line">};</span><br><span class="line"></span><br><span class="line">Function<String, String> function = <span class="keyword">new</span> Function<String,String>(){</span><br><span class="line"> <span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> String <span class="title">apply</span><span class="params">(String input)</span> </span>{</span><br><span class="line"> <span class="keyword">return</span> input.toUpperCase();</span><br><span class="line"> }</span><br><span class="line">};</span><br><span class="line"></span><br><span class="line">List<String> list = Lists.newArrayList(<span class="string">"java"</span>, <span class="string">"c#"</span>, <span class="string">"javascript"</span>, <span class="string">"python"</span>);</span><br><span class="line">ImmutableList<String> result = FluentIterable.from(list)</span><br><span class="line"> .filter(predicate)</span><br><span class="line"> .transform(function)</span><br><span class="line"> .toList();</span><br><span class="line"></span><br><span class="line">System.out.println(result); <span class="comment">// [JAVA, JAVASCRIPT]</span></span><br></pre></td></tr></table></figure><p></p><h2 id="Iterables"><a href="#Iterables" class="headerlink" title="Iterables"></a>Iterables</h2><p>除了上面涉及的Iterables的用法外,其还提供了许多别的好用的方法。</p><h3 id="removeAll"><a href="#removeAll" class="headerlink" title="removeAll"></a>removeAll</h3><p>该方法用于从特定集合中删除给定集合中的元素:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">List<String> removeFrom = Lists.newArrayList(<span class="string">"a"</span>, <span class="string">"b"</span>, <span class="string">"c"</span>);</span><br><span class="line">List<String> elementsToRemove = Lists.newArrayList(<span class="string">"b"</span>, <span class="string">"c"</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">boolean</span> result = Iterables.removeAll(removeFrom, elementsToRemove);</span><br><span class="line">System.out.println(result); <span class="comment">// true</span></span><br><span class="line">System.out.println(removeFrom); <span class="comment">// [a]</span></span><br></pre></td></tr></table></figure><p></p><h3 id="retainAll"><a href="#retainAll" class="headerlink" title="retainAll"></a>retainAll</h3><p>retainAll的功能和removeAll相反:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">List<String> removeFrom = Lists.newArrayList(<span class="string">"a"</span>, <span class="string">"b"</span>, <span class="string">"c"</span>);</span><br><span class="line">List<String> elementsToRetain = Lists.newArrayList(<span class="string">"b"</span>, <span class="string">"c"</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">boolean</span> result = Iterables.retainAll(removeFrom, elementsToRetain);</span><br><span class="line">System.out.println(result); <span class="comment">// true</span></span><br><span class="line">System.out.println(removeFrom); <span class="comment">// [b, c]</span></span><br></pre></td></tr></table></figure><p></p><h3 id="addAll"><a href="#addAll" class="headerlink" title="addAll"></a>addAll</h3><p>addAll用于将给定集合添加到现有集合中:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">List<String> list1 = Lists.newArrayList(<span class="string">"a"</span>, <span class="string">"b"</span>, <span class="string">"c"</span>);</span><br><span class="line">List<String> list2 = Lists.newArrayList(<span class="string">"b"</span>, <span class="string">"c"</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">boolean</span> b = Iterables.addAll(list1, list2); <span class="comment">// true</span></span><br><span class="line">System.out.println(list1); <span class="comment">// [a, b, c, b, c]</span></span><br></pre></td></tr></table></figure><p></p><h3 id="concat"><a href="#concat" class="headerlink" title="concat"></a>concat</h3><p>concat用于合并集合,组成一个新的集合对象:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">List<String> list1 = Lists.newArrayList(<span class="string">"a"</span>, <span class="string">"b"</span>, <span class="string">"c"</span>);</span><br><span class="line">List<String> list2 = Lists.newArrayList(<span class="string">"b"</span>, <span class="string">"c"</span>);</span><br><span class="line"></span><br><span class="line">Iterable<String> result = Iterables.concat(list1,list2);</span><br><span class="line">System.out.println(result); <span class="comment">// [a, b, c, b, c]</span></span><br></pre></td></tr></table></figure><p></p><p>Iterables还包含许多别的实用方法:</p><p><img src="img/QQ截图20190423231111.png" alt="QQ截图20190423231111.png"></p><p>这里就不一一演示了,溜了。</p><p><img src="img/QQ图片20190423231252.png" alt="QQ图片20190423231252.png"></p><p>更详细的内容可以参考guava官方wiki:<a href="https://github.com/google/guava/wiki" target="_blank" rel="noopener">https://github.com/google/guava/wiki</a></p><script>$(".post-body a").not(".thispage").addClass("ignore-href").attr("target","_blank")</script></div><div></div><div><div style="padding:10px 0;margin:20px auto;width:90%;text-align:center;color:#878787" id="reward-div"><div>请作者喝瓶肥宅水🥤</div><button id="rewardButton" style="margin-top:10px" disable="enable" onclick='var e=document.getElementById("QR");"none"===e.style.display?e.style.display="block":e.style.display="none"'><span style="height:46px;width:46px;line-height:46px;border-radius:50%;color:#fe5f55;font-weight:600;background:#ffd5be;border:none;box-shadow:0 4px 8px 0 rgba(255,213,190,.4)">¥</span></button><div id="QR" style="display:none"><div id="wechat" style="display:inline-block"><img id="wechat_qr" src="/img/wechat_pay.png" alt="MrBird WeChat Pay"></div><div id="alipay" style="display:inline-block"><img id="alipay_qr" src="/img/ali_pay.png" alt="MrBird Alipay"></div></div></div><style>#QR img{width:auto;margin:.8em 1em 0 1em}</style></div><div><ul class="post-copyright"><li class="post-copyright-author"><strong>本文作者:</strong> MrBird</li><li class="post-copyright-link"><strong>本文链接:</strong> <a href="http://mrbird.cc/Guava-Collection.html" title="Guava 集合操作">http://mrbird.cc/Guava-Collection.html</a></li><li class="post-copyright-license"><strong>版权声明: </strong>本博客所有文章除特别声明外,均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处!</li></ul></div><footer class="post-footer"><div class="post-tags" style="margin-bottom:1.3rem"><a href="/tags/guava/" rel="tag"># guava</a></div><div class="post-nav"><div class="post-nav-next post-nav-item"><a href="/FEBS-Vue-Document.html" rel="next" title="FEBS-Vue文档"><i class="fa fa-chevron-left"></i> FEBS-Vue文档</a></div><span class="post-nav-divider"></span><div class="post-nav-prev post-nav-item"><a href="/Guava-Cache.html" rel="prev" title="Guava 缓存">Guava 缓存 <i class="fa fa-chevron-right"></i></a></div></div></footer></article><hr><div id="container"></div><div class="post-spread"><div id="comment-div"></div><style>.valine .vlist{margin-bottom:3rem}.valine .vwrap .vcontrol .col.col-60{text-align:left}.valine .vlist .vcard .vhead,.valine .vlist .vcard section .vfooter{text-align:left}.valine .vlist .vcard section{padding-bottom:.5rem!important}.vname{color:#6db33f!important}div#comment-div{margin-bottom:-8rem}.valine .vlist .vcard .vcontent .code,.valine .vlist .vcard .vcontent code,.valine .vlist .vcard .vcontent pre{background:#fbfbfb}.valine .vlist .vcard .vcontent a{color:#6db33f}.valine .vlist .vcard .vimg{border-radius:3px}.valine .vinfo{text-align:left}.valine .vbtn{border-radius:2px;padding:.3rem 1.25rem}.valine .vbtn:active,.valine .vbtn:hover{color:#6db33f;border-color:#6db33f;background-color:#fff}.valine .vwrap .vheader .vinput:focus{border-bottom-color:#6db33f}.valine .vlist .vcard .vcontent.expand:before{background:-webkit-gradient(linear,left top,left bottom,from(hsla(0,0%,100%,0)),to(hsla(0,0%,100%,.2)));background:linear-gradient(180deg,hsla(0,0%,100%,0),hsla(0,0%,100%,.2))}.valine .vlist .vcard .vcontent.expand:after{content:"点击展开";font-size:.4rem;text-align:right;left:-1rem;background:hsla(0,0%,100%,.2)}.valine .vlist .vcard section .vfooter .vat{color:#b3b3b3}.valine .vlist .vcard section .vfooter .vat:hover{color:#6db33f}.vcontent img{margin:0}.valine .info{display:none}</style><script type="text/javascript" src="/js/av.min.js"></script><script type="text/javascript" src="/js/Valine.min.js"></script><script type="text/javascript" src="/js/activate-power-mode.js"></script><script>POWERMODE.colorful=!0,POWERMODE.shake=!1,document.body.addEventListener("input",POWERMODE),new Valine({el:"#comment-div",notify:!1,verify:!0,appId:"SMcDFP1bN1jgb9Lo8JmtICHm-gzGzoHsz",appKey:"dH4nrUrt3V5XiJiI6Qyejnbi",placeholder:"",path:window.location.pathname,avatar:"monsterid",guest_info:["nick","mail","link"]});var chicken='<a href="#"><img src="https://image.uisdc.com/wp-content/uploads/2018/06/uisdc-chat-chicken.gif" class="checken"></a>';$("#comment-div").prepend(chicken)</script></div></div><script>var $bqinline=$("img[alt='bq-inline']");$bqinline.css({width:"2.3rem",height:"2.3rem",display:"inline","vertical-align":"text-bottom"})</script></div><div class="comments" id="comments"></div></div><aside id="sidebar" class="sidebar" onselectstart="return!1"><div class="sidebar-inner"><ul class="sidebar-nav motion-element"><li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">Contents</li><li class="sidebar-nav-overview" data-target="site-overview">Site Preview</li></ul><section class="site-overview sidebar-panel"><div class="sidebar-sticky sticky"><div itemscope itemtype="https://mrbird.cc"><div class="author__header"><div class="author__avatar"><img src="/images/blogImage.jpg" class="author__avatar" alt="MrBird" itemprop="image"></div><div class="author__content"><div class="author__name" itemprop="name">MrBird</div><p class="author__bio" itemprop="description">A simple blog, code repository, just keep blogging</p></div><div class="author__count"><a href="/archives" class="ignore-href"><span class="count">14</span> <span>Archives</span> </a><a href="/tags" class="ignore-href"><span class="count">2</span> <span>Labels</span></a></div></div><div class="author__urls-wrapper"><ul class="author__urls social-icons"><li><a href="/" itemprop="url" class="ignore-href">🏠 Home</a></li><li><a href="/archives" itemprop="url" class="ignore-href">📦 Archives</a></li><li><a href="/tags" itemprop="url" class="ignore-href">🔖 Labels</a></li><li><a href="/friends" itemprop="url" class="ignore-href">👬 Friends</a></li><li><a href="javascript:;" class="popup-trigger animsition-link">🔍 Search</a></li></ul></div></div></div></section><section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active"><div class="post-toc"><div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#不可变集合"><span class="nav-number">1.</span> <span class="nav-text">不可变集合</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#创建不可变集合"><span class="nav-number">1.1.</span> <span class="nav-text">创建不可变集合</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#不可变集合优点"><span class="nav-number">1.2.</span> <span class="nav-text">不可变集合优点</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#新集合类型"><span class="nav-number">2.</span> <span class="nav-text">新集合类型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#RangeSet"><span class="nav-number">2.1.</span> <span class="nav-text">RangeSet</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#RangeMap"><span class="nav-number">2.2.</span> <span class="nav-text">RangeMap</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#BiMap"><span class="nav-number">2.3.</span> <span class="nav-text">BiMap</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Table"><span class="nav-number">2.4.</span> <span class="nav-text">Table</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Multiset"><span class="nav-number">2.5.</span> <span class="nav-text">Multiset</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Multimap"><span class="nav-number">2.6.</span> <span class="nav-text">Multimap</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ClassToInstanceMap"><span class="nav-number">2.7.</span> <span class="nav-text">ClassToInstanceMap</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Lists、Maps-amp-Sets"><span class="nav-number">3.</span> <span class="nav-text">Lists、Maps&Sets</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Lists"><span class="nav-number">3.1.</span> <span class="nav-text">Lists</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Sets"><span class="nav-number">3.2.</span> <span class="nav-text">Sets</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Maps"><span class="nav-number">3.3.</span> <span class="nav-text">Maps</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Joiner与Splitter"><span class="nav-number">4.</span> <span class="nav-text">Joiner与Splitter</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Joiner"><span class="nav-number">4.1.</span> <span class="nav-text">Joiner</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Splitter"><span class="nav-number">4.2.</span> <span class="nav-text">Splitter</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Filter-amp-Transform"><span class="nav-number">5.</span> <span class="nav-text">Filter&Transform</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Filter"><span class="nav-number">5.1.</span> <span class="nav-text">Filter</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Transform"><span class="nav-number">5.2.</span> <span class="nav-text">Transform</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Iterables"><span class="nav-number">6.</span> <span class="nav-text">Iterables</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#removeAll"><span class="nav-number">6.1.</span> <span class="nav-text">removeAll</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#retainAll"><span class="nav-number">6.2.</span> <span class="nav-text">retainAll</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#addAll"><span class="nav-number">6.3.</span> <span class="nav-text">addAll</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#concat"><span class="nav-number">6.4.</span> <span class="nav-text">concat</span></a></li></ol></li></ol></div></div></section></div><div id="asider-footer"><div id="links"><li><a href="https://love.mrbird.cc" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-diamond" aria-hidden="true"></i></a></li><li><a href="https://cloud.mrbird.cn" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-skyatlas" aria-hidden="true"></i></a></li><li><a href="https://gitee.com/mrbirdd" target="_blank" itemprop="sameAs" class="ignore-href"><i class="fa fa-fw fa-codepen" aria-hidden="true"></i></a></li><li><a href="https://github.com/wuyouzhuguli" target="_blank" itemprop="sameAs" class="ignore-href"><i class="fa fa-fw fa-github-alt" aria-hidden="true"></i></a></li></div><div id="author"></div><script type="text/javascript">var $smsheoschzd100dn="@ 2016 - "+(new Date).getFullYear()+" MrBird";document.getElementById("author").innerHTML=$smsheoschzd100dn</script><div><script type="text/javascript" src="/js/busuanzi.js"></script> UV <span class="busuanzi-value" id="busuanzi_value_site_uv" style="cursor:pointer" title="统计开始时间:2019年7月5日"></span> PV <span class="busuanzi-value" id="busuanzi_value_site_pv" style="cursor:pointer" title="统计开始时间:2019年7月5日"></span></div></div><script>function c__(){var o=sidebar_nav_toc.attr("class");o.indexOf("active")!=-1?footer.hide(300):footer.show(300)}var sidebar_nav_toc=$(".sidebar-nav-toc"),footer=$("#asider-footer");c__(),$(".sidebar-nav").on("click",function(){c__()})</script></aside></div></main><div class="back-to-top"><span id="scrollpercent"><span>0</span></span></div></div><script type="text/javascript">"[object Function]"!==Object.prototype.toString.call(window.Promise)&&(window.Promise=null)</script><script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script><script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script><script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script><script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script><script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script><script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script><script type="text/javascript">function proceedsearch(){$("body").append('<div class="search-popup-overlay local-search-pop-overlay"></div>').css("overflow","hidden"),$(".search-popup-overlay").click(onPopupClose),$(".popup").toggle();var t=$("#local-search-input");t.attr("autocapitalize","none"),t.attr("autocorrect","off"),t.focus()}var isfetched=!1,isXml=!0,search_path="search.xml";0===search_path.length?search_path="search.xml":search_path.endsWith("json")&&(isXml=!1);var path="/"+search_path,onPopupClose=function(t){$(".popup").hide(),$("#local-search-input").val(""),$(".search-result-list").remove(),$("#no-result").remove(),$(".local-search-pop-overlay").remove(),$("body").css("overflow","")},searchFunc=function(t,e,o){"use strict";$("body").append('<div class="search-popup-overlay local-search-pop-overlay"><div id="search-loading-icon"><i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i></div></div>').css("overflow","hidden"),$("#search-loading-icon").css("margin","20% auto 0 auto").css("text-align","center"),$.ajax({url:t,dataType:isXml?"xml":"json",async:!0,success:function(t){isfetched=!0,$(".popup").detach().appendTo(".header-inner");var n=isXml?$("entry",t).map(function(){return{title:$("title",this).text(),content:$("content",this).text(),url:$("url",this).text()}}).get():t,r=document.getElementById(e),s=document.getElementById(o),a=function(){var t=r.value.trim().toLowerCase(),e=t.split(/[\s\-]+/);e.length>1&&e.push(t);var o=[];if(t.length>0&&n.forEach(function(n){function r(e,o,n,r){for(var s=r[r.length-1],a=s.position,i=s.word,l=[],h=0;a+i.length<=n&&0!=r.length;){i===t&&h++,l.push({position:a,length:i.length});var p=a+i.length;for(r.pop();0!=r.length&&(s=r[r.length-1],a=s.position,i=s.word,p>a);)r.pop()}return c+=h,{hits:l,start:o,end:n,searchTextCount:h}}function s(t,e){var o="",n=e.start;return e.hits.forEach(function(e){o+=t.substring(n,e.position);var r=e.position+e.length;o+='<b class="search-keyword">'+t.substring(e.position,r)+"</b>",n=r}),o+=t.substring(n,e.end)}var a=!1,i=0,c=0,l=n.title.trim(),h=l.toLowerCase(),p=n.content.trim().replace(/<[^>]+>/g,""),u=p.toLowerCase(),f=decodeURIComponent(n.url),d=[],g=[];if(""!=l&&(e.forEach(function(t){function e(t,e,o){var n=t.length;if(0===n)return[];var r=0,s=[],a=[];for(o||(e=e.toLowerCase(),t=t.toLowerCase());(s=e.indexOf(t,r))>-1;)a.push({position:s,word:t}),r=s+n;return a}d=d.concat(e(t,h,!1)),g=g.concat(e(t,u,!1))}),(d.length>0||g.length>0)&&(a=!0,i=d.length+g.length)),a){[d,g].forEach(function(t){t.sort(function(t,e){return e.position!==t.position?e.position-t.position:t.word.length-e.word.length})});var v=[];0!=d.length&&v.push(r(l,0,l.length,d));for(var C=[];0!=g.length;){var $=g[g.length-1],m=$.position,x=$.word,w=m-20,y=m+80;w<0&&(w=0),y<m+x.length&&(y=m+x.length),y>p.length&&(y=p.length),C.push(r(p,w,y,g))}C.sort(function(t,e){return t.searchTextCount!==e.searchTextCount?e.searchTextCount-t.searchTextCount:t.hits.length!==e.hits.length?e.hits.length-t.hits.length:t.start-e.start});var T=parseInt("1");T>=0&&(C=C.slice(0,T));var b="";b+=0!=v.length?"<li><a href='"+f+"' class='search-result-title'>"+s(l,v[0])+"</a>":"<li><a href='"+f+"' class='search-result-title'>"+l+"</a>",C.forEach(function(t){b+="<a href='"+f+'\'><p class="search-result">'+s(p,t)+"...</p></a>"}),b+="</li>",o.push({item:b,searchTextCount:c,hitCount:i,id:o.length})}}),1===e.length&&""===e[0])s.innerHTML='<div id="no-result"><i class="fa fa-search fa-5x" /></div>';else if(0===o.length)s.innerHTML='<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>';else{o.sort(function(t,e){return t.searchTextCount!==e.searchTextCount?e.searchTextCount-t.searchTextCount:t.hitCount!==e.hitCount?e.hitCount-t.hitCount:e.id-t.id});var a='<ul class="search-result-list">';o.forEach(function(t){a+=t.item}),a+="</ul>",s.innerHTML=a}};r.addEventListener("input",a),$(".local-search-pop-overlay").remove(),$("body").css("overflow",""),proceedsearch()}})};$(".popup-trigger").click(function(t){t.stopPropagation(),isfetched===!1?searchFunc(path,"local-search-input","local-search-result"):proceedsearch()}),$(".popup-btn-close").click(onPopupClose),$(".popup").click(function(t){t.stopPropagation()}),$(document).on("keyup",function(t){var e=27===t.which&&$(".search-popup").is(":visible");e&&onPopupClose()})</script></body><script>$(function(){$("a").not(".nav-link,.cloud-tie-join-count,.ignore-href,.jstree-anchor").addClass("animsition-link")});var burst1=new mojs.Burst({left:0,top:0,radius:{5:40},children:{shape:"circle",fill:["red","cyan","orange"],fillOpacity:.8,radiusX:3.5,radiusY:3.5}});document.addEventListener("click",function(a){null==a.target.href&&"footer"!=a.target.className&&"copyright"!=a.target.className&&"author__urls social-icons"!=a.target.className&&"author__avatar"!=a.target.className&&"sidebar sidebar-active"!=a.target.className&&burst1.tune({x:a.pageX,y:a.pageY}).generate().replay()})</script><script type="text/javascript" src="/js/message.js"></script></html><!-- rebuild by neat -->