guava 集合和函数接口妙用

2019-04-16 14:24:02 浏览数 (1)

代码语言:javascript复制
//利用partition进行对数据进行分组
	@Test
	public void test26(){
		List<String> list = ImmutableList.of("hello", "HI", "Hey");
		List<List<String>> partition = Lists.partition(list, 2);
		System.out.println(partition);
	}

//Lists中的transform方法(通过函数式接口)能够对数据进行处理
	@Test
	public void test25(){
		List<String> list = ImmutableList.of("hello", "HI", "Hey");
		List<String> transform = Lists.transform(list, new Function<String, String>() {
			@Override
			public String apply(String input) {
				if(input.contentEquals("HI"))
					System.out.println(input);
				return input;
			}
		});
		System.out.println(transform);
	}

//通过函数式接口,把处理后的数据放到一个map中
	// 根据特征进行筛选集合中的数据
	@Test
	public void test12() {
		ImmutableSet<String> digits = ImmutableSet.of("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine");
		Function<String, Integer> lengthFunction = new Function<String, Integer>() {
			public Integer apply(String string) {
				return string.length();
			}
		};
		ImmutableListMultimap<Integer, String> digitsByLength = Multimaps.index(digits, lengthFunction);
		System.out.println(digitsByLength);
		/*
		 * digitsByLength maps: 3 => {"one", "two", "six"} 4 => {"zero", "four",
		 * "five", "nine"} 5 => {"three", "seven", "eight"}
		 */
	}

0 人点赞