Multiset:无序可重复set,重复元素显示个数 还是挺有用的数据结构
@Test void test5() { String s = "good good study day day up"; String[] s1 = s.split(" "); HashMultiset<String> multiset = HashMultiset.create(); multiset.addAll(Arrays.asList(s1)); System.out.println(multiset);//[study, up, good x 2, day x 2] multiset.forEach(e -> { System.out.println(e + "->" + multiset.count(e)); /* study->1 up->1 good->2 good->2 day->2 day->2 */ }); }
Multimap:key可重复的map(我理解就是Map<String, Set<String>这种结构)
@Test
void test6() {
//需求:统计每个作者有几本书
HashMap<String, String> map = new HashMap<>();
map.put("Java从入门到精通", "bin"); //书名:作者
map.put("Java从入门到精通", "bin"); //书名:作者
map.put("Android从入门到精通", "bin"); //书名:作者
map.put("PHP从入门到精通", "jack"); //书名:作者
map.put("笑看人数", "vince"); //书名:作者
Multimap<String, String> mmap = ArrayListMultimap.create();
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> next = iterator.next();
mmap.put(next.getValue(), next.getKey());
}
System.out.println(mmap);//{bin=[Java从入门到精通, Android从入门到精通], vince=[笑看人数], jack=[PHP从入门到精通]}
Set<String> strings = mmap.keySet();
strings.forEach(e -> {
System.out.println(e + " -> " +mmap.get(e));
});
/**
* bin -> [Java从入门到精通, Android从入门到精通]
* vince -> [笑看人数]
* jack -> [PHP从入门到精通]
*/
}
求集合交集、并集、差集,非常好用
@Test void test4() { HashSet<Integer> set1 = Sets.newHashSet(1, 2, 3); HashSet<Integer> set2 = Sets.newHashSet(3, 4, 5); Sets.SetView<Integer> intersection = Sets.intersection(set1, set2); System.out.println(intersection); //[3] Sets.SetView<Integer> difference = Sets.difference(set1, set2); System.out.println(difference);//[1, 2] Sets.SetView<Integer> union = Sets.union(set1, set2); System.out.println(union);//[1, 2, 3, 4, 5] }
未完待续......
标签:map,入门,System,println,Sets,集合,Guava,类中,out From: https://www.cnblogs.com/wscw/p/17124975.html