@Test
public void test(){
String str = "abcccddddddds";
//这一步,将字符串变成list,具体思路的话是变成char数组,再变成list
List<String> list = Lists.newArrayList();
for(int i=0,length=str.toCharArray().length;i<length;++i){
list.add(String.valueOf(str.toCharArray()[i]));
}
//建立set的目的是等会作为map的key
Set<String> set = new LinkedHashSet<>(list);
//创建一个可以计数的set,具体见guava文档(文末提示)
HashMultiset hashMultiset = HashMultiset.create(list);
int count;
//这个map的key为字母,value为出现的次数
Map<String, Integer> map = new LinkedHashMap();
for(String s:set){
count = hashMultiset.count(s);
map.put(s,count);
}
//找出出现次数的最大值
Collection<Integer> li = map.values();
Integer max = li.stream().max(Integer::compareTo).get();
String key = null;
//根据最大值找到第一次出现的字母
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if(max.equals(entry.getValue())){
key=entry.getKey();
break;
}
}
System.out.println(key);
}
// //guava集合
Lists.newArrayList("1","2").forEach(d-> System.out.println(d));
// //guava字符串
System.out.println(Strings.emptyToNull(""));
// //Objects
System.out.println(Objects.isNull(null));
//ImmutableMap为不可变map,意思就是key1再put的话不能覆盖了
ImmutableMap.of("key1","value1","key2","value2").entrySet().stream().
peek(d-> System.out.println(d.getValue())).collect(Collectors.toList());
//multimap:重复的key会组成list
ArrayListMultimap<String,String> map = ArrayListMultimap.create();
map.put("1","2");
map.put("1","2");
System.out.println(map.get("1"));//[2, 2]
//multiSet允许重复,并且可以求某个元素重复个数
ArrayList arrayList = Lists.newArrayList("1","2","2","3","4","1");
HashMultiset set = HashMultiset.create(arrayList);
System.out.println(set.count("2"));
//求出哪个是重复元素
Set obj = (Set)set.stream().filter(d->set.count(d)>1).collect(Collectors.toSet());
System.out.println(obj);
//biMap通过key可以获取value,通过value可以获取key
BiMap<String,String> bi = HashBiMap.create();
bi.put("1","2");
bi.put("2","3");
System.out.println(bi.inverse().get("3"));
package com.guahao.dap.workbench.external.support.txyb;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
/**
* @author fangyou
* @version V1.0
* @since 2021/12/2 17:36
*/
public class TestMain {
public static void main(String[] args) {
String str = "asasasacccdasdsa";
ArrayList<String> arrayList = Lists.newArrayList();
for(int i =0,length = str.toCharArray().length;i<length;++i){
arrayList.add(String.valueOf(str.toCharArray()[i]));
}
HashMultiset hashMultiset = HashMultiset.create(arrayList);
HashMap<String, Integer> hashMap = Maps.newHashMap();
arrayList.stream().forEach(e -> {
hashMap.put(e,hashMultiset.count(e));
});
Collection<Integer> c = hashMap.values();
Integer max = c.stream().max(Integer::compareTo).get();
hashMap.entrySet().forEach(e->{
if(Math.abs(max-e.getValue())==0){
System.out.println(e.getKey());
}
});
}
}