台市住房和城乡建设局网站/长沙今日头条新闻
本文目录
- 统计文本中各种单词出现的次数。
- 网络请求
- 多信息上报
- 多条件查询
- EventBus
- 缓存
统计文本中各种单词出现的次数。
下面是简化的java代码
import java.util.HashMap;
import java.util.Map;public class HashMapTest {public static void main(String[] args) {String text = "hello world hello my name is jack her name is anna";String[] words = text.split(" "); // 将文本按空格分隔成单词数组Map<String, Integer> wordCountMap = new HashMap<>();for (String word : words) {if (wordCountMap.containsKey(word)) { // 如果map中已经存在该单词,则增加计数int count = wordCountMap.get(word);wordCountMap.put(word, count + 1);} else { // 如果map中不存在该单词,则添加到map,并设置计数为1wordCountMap.put(word, 1);}}// 遍历输出每个单词出现的次数for (String key : wordCountMap.keySet()) {int count = wordCountMap.get(key);System.out.println(key + ": " + count);}}
}
网络请求
多信息上报
appId: 1234
channel: oppo/huawei
appVersion: 0.0.1
systemType: android/ios
userName: jack/null
上面的参数总数不固定,比如:没有上架前channel参数可以不传,未登录的情况下userName也可以不传。这个时候就可以用HashMap作为参数,发送给后端。
多条件查询
比如获取某个城市某个区某个地铁站附近500米以内的所有单间。
city:深圳市
district: 宝安区
subway_station: 宝安中心
distance: 500
house_type: 单间
这些条件,如果是可以增减的,条件总数量不确定。就可以用一个HashMap作为参数,传递给后端。
Retrofit库具体使用,可以参考这篇:Retrofit2系列:简单的Get请求。
其中,@Body
和@QueryMap
这两个入参注解,后面都可以跟HashMap。例如:
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);@POST
Call<User> getDataFromServer(@Url String url, @Body HashMap<String,Object> hashMap);
关于retrofit注解,可以参考:retrofit官方文档。
EventBus
EventBus 中有多处用到HashMap,采用HashMap把event和订阅了这个event的对象集合存储起来,key是event对象的.class对象,value是CopyOnWriteArrayList。
关于EventBus的具体细节可以参考:EventBus实现组件通信的原理
源码如下:
public class EventBus {/** Log tag, apps may override it. */public static String TAG = "EventBus";...//下面的构造器中用到private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();private static final Map<Class<?>, List<Class<?>>> eventTypesCache = new HashMap<>();//这个是核心HashMap在下面的构造器里面赋值private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;...public static EventBusBuilder builder() {return new EventBusBuilder();}public EventBus() {this(DEFAULT_BUILDER);}EventBus(EventBusBuilder builder) {...//在这里new 了个HashMap对象subscriptionsByEventType = new HashMap<>();typesBySubscriber = new HashMap<>();...}}
缓存
一般缓存使用LinkedHashMap,LinkedHashMap继承自HashMap,所以也可以说缓存用的也是HashMap。
public class LinkedHashMap<K,V>extends HashMap<K,V>implements Map<K,V>
{......
}
Glide图片缓存。缓存比较复杂,后面有时间再讲。