前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java 8里的Predicate学习笔记

Java 8里的Predicate学习笔记

作者头像
Jerry Wang
发布2020-04-24 10:34:30
6110
发布2020-04-24 10:34:30
举报

测试代码:

MapTest maptest = new MapTest();
		List<Country> testdata = maptest.getCountry();
		
		Map<String, Country> result1 = maptest.getCountryDataMap(testdata);
		Map<String, Country> result2 = maptest.getCountryDataMap2(testdata);
		
		Stream<Country> temp = testdata.stream();
		Predicate<Country> match = country -> country.getCode().equals("US"); 
		Stream<Country> result = temp.filter(match);
		System.out.println("Size 2: " + result.count());
		List<Country> filterResult = testdata.stream().filter((country) -> country.getCode().equals("US")).collect(Collectors.toList());
		System.out.println("size: " + filterResult.size());
		filterResult.forEach(System.out::println);
		System.out.println(maptest.assertEqual2(result1, result2));

Predicate的源代码:

/**
 * Represents a predicate (boolean-valued function) of one argument.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #test(Object)}.
 *
 * @param <T> the type of the input to the predicate
 *
 * @since 1.8
 */

Predicate接受一个类型作为参数,返回布尔值。

因此代码里我就可以使用第113行这种箭头函数,country为箭头函数或者说Lambda Function里的形式参数(输入参数),因为Predicate接收的泛型参数为T- Country,所以编译器能断定,形式参数的类型一定为Country.

最后用collect,传入Collectors.toList().

collect方法将传入的Collector施加到stream的元素内,

Collectors.toList的操作:将流里的元素添加到一个List容器里并返回。

Returns a Collector that accumulates the input elements into a new List. There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned

完整的测试代码:

package java8.forHybrisCodeReview;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

class Country{
	private String mCountryCode;
	private int mRank;
	public Country(String mCode, int rank){
		this.mCountryCode = mCode;
		this.mRank = rank;
	}
	
	public String getCode(){
		return this.mCountryCode;
	}
	
	@Override
    public boolean equals(Object other) {
        if( other == null)
        	return false;
        
        if ( !(other instanceof Country) )
        	return false;
        Country country = (Country)other;
        return this.mCountryCode.equals(country.mCountryCode) && this.mRank == country.mRank;
    }
	
	@Override
    public int hashCode() {
        return this.mCountryCode.hashCode()*37 + this.mRank;
    }
}
public class MapTest{
	public List<Country> getCountry(){
		List<Country> countries = new ArrayList<Country>();
		
		Country country = new Country("ZH", 1);
		countries.add(country);
		
		country = new Country("US", 2);
		countries.add(country);
		
		country = new Country("JP", 3);
		countries.add(country);
		return countries;
	}
	
	public Map<String, Country> getCountryDataMap(List<Country> countryList)
	{
		final Map<String, Country> countryDataMap = new HashMap<>();
		for (final Country countryData : countryList){
			countryDataMap.put(countryData.getCode(), countryData);
		}
		return countryDataMap;
	}
	
	public Map<String, Country> getCountryDataMap2(List<Country> countryList)
	{
		final Map<String, Country> countryDataMap = new HashMap<>();
		
		Consumer<Country> consumer = c -> countryDataMap.put(c.getCode(), c);
		countryList.forEach(consumer);
		return countryDataMap;
	}
	
	// forEach之所以被称为内部遍历器,原因在于一旦它开始执行了,那么遍历操作就不能够被轻易中断。
	public boolean assertEqual(Map<String, Country> map1, Map<String, Country> map2){
		if( map1.size() != map2.size())
			return false;
		final boolean equal = true;
		map1.forEach((key, value)->
		{
			System.out.println("key of map1:" + key);
			Country country = map2.get(key);
			if( !value.equals(country)){
				
			}
				// Void methods cannot return a value
				// return false;
				// equal = false; // cannot change final
		});
		return equal;
	}
	
	public boolean assertEqual2(Map<String, Country> map1, Map<String, Country> map2){
		if( map1.size() != map2.size())
			return false;
		for (Map.Entry<String,Country> entry : map1.entrySet()) {
		    String key = entry.getKey();
		    Country country = entry.getValue();
		    Country country2 = map2.get(key);
		    if( !country.equals(country2))
		    	return false;
		}
		return true;
    }

	public static void main(String[] arg){
		MapTest maptest = new MapTest();
		List<Country> testdata = maptest.getCountry();
		
		Map<String, Country> result1 = maptest.getCountryDataMap(testdata);
		Map<String, Country> result2 = maptest.getCountryDataMap2(testdata);
		
		Stream<Country> temp = testdata.stream();
		Predicate<Country> match = country -> country.getCode().equals("US"); 
		Stream<Country> result = temp.filter(match);
		System.out.println("Size 2: " + result.count());
		List<Country> filterResult = testdata.stream().filter((country) -> country.getCode().equals("US")).collect(Collectors.toList());
		System.out.println("size: " + filterResult.size());
		filterResult.forEach(System.out::println);
		System.out.println(maptest.assertEqual2(result1, result2));
	}
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-04-23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档