note: Guava-22

 

public class GuavaDemo {

	/**
	 * 只读数组
	 */
	@Test
	public void guava1() {
		
		// 创建定长不可修改的数组, 即"只读"
		// 方法一:
		List names = Arrays.asList("lee1", "lee2", "lee3");
		names.add("lee4"); // UnsupportedOperationException
		List list = new ArrayList<>(names);
		// 方法二:
		List cpList = Collections.unmodifiableList(list);
		cpList.add("lee4"); // UnsupportedOperationException
		// 方法三:
		ImmutableList iList = ImmutableList.of("lee5", "lee6", "lee7");
		iList.add("lee8"); // UnsupportedOperationException
	}
	
	/**
	 * 过滤器
	 */
	@Test
	public void guava2() {
		List names = Arrays.asList("lee1", "lee2", "lee3", "java", "json", "php", "c++");
		Collections2.filter(names, (e) -> e.startsWith("j")).forEach(System.out::println);
	}
	
	/**
	 * 转换
	 */
	@Test
	public void guava3() {
		Set DateSet = Sets.newHashSet(20190919L, 20190920L, 20190921L);
		Collections2.transform(DateSet, (e) -> new SimpleDateFormat("yyyy-MM-dd").format(e))
				.forEach(System.out::println); // output error!
		 
	}
	
	/**
	 * 组合式函数
	 */
	@Test
	public void guava4() {
		List names = Arrays.asList("lee1", "lee2", "lee3", "java", "json", "php", "c++");
		Function func1 = new Function() {
			
			@Override
			public String apply(String s) {
				return s.length() > 3 ? s.substring(0, 2) : s;
			}
		};
		Function func2 = new Function() {

			@Override
			public String apply(String s) {
				return s.toUpperCase();
			}
		};
		Function funcCps = Functions.compose(func1, func2);
		Collections2.transform(names, funcCps).forEach(System.out::println);;
		
	}
	
	/**
	 * HashMultiset 无序可重复
	 */
	@Test
	public void guava7() {
		String s = "java c c++ c php golang java javascript golang golang";
		String[] split = s.split(" ");
		HashMultiset set = HashMultiset.create();
		for (String string : split) {
			set.add(string);
		}
		Set set2 = set.elementSet();
		for (String string : set2) {
			System.out.println(string + " cnt:" + set.count(string));
		}
	}
	
	@Test
	public void guava8() {
		Map map = new HashMap<>();
		map.put("think in java", "aaa");
		map.put("think in c++", "aaa");
		map.put("java design partten", "bbb");
		
		ArrayListMultimap mmap = ArrayListMultimap.create();
		Iterator> entrySet = map.entrySet().iterator();
		while (entrySet.hasNext()) {
			Map.Entry entry = entrySet.next();
			mmap.put(entry.getValue(), entry.getKey());
		}
		for (String str : mmap.keySet()) {
			List values = mmap.get(str);
			System.out.println(str + "=" + values);
		}
	}
}

 

你可能感兴趣的:(guava-22,guava)