当前位置:网站首页>普歌 -- getOrDefault()方法理解
普歌 -- getOrDefault()方法理解
2022-06-28 06:29:00 【Dear-JC】
解析getOrDefault()方法
介绍
getOrDefault(Object key, V defaultValue)
在操作Map集合时,判断是否存储着这个key。如果有返回对应的value值,若不存在,则返回自定义的默认值defaultValue值。
代码实现
LeetCode第387题:字符串中第一个唯一字符
public static void main(String[] args) {
String s = "loveleetcode";
System.out.println(firstUniqChar(s));
}
public static int firstUniqChar(String s) {
Map<Character, Integer> frequency = new HashMap<Character, Integer>();
for (int i = 0; i < s.length(); ++i) {
char ch = s.charAt(i);
// 当集合中这个key时,就使用这个value值,没有默认defaultValue
frequency.put(ch, frequency.getOrDefault(ch, 0) + 1); // 将前面的值放进去,按默认值+1计算,只有当出现重复的时候再按ch的value计算。
}
for (int i = 0; i < s.length(); ++i) {
if (frequency.get(s.charAt(i)) == 1) {
// 返回指定的字符,将字符当作key进行返回
return i;
}
}
return -1; // 返回最末的值
}
完结
边栏推荐
- 借助nz-pagination中的let-total解析ng-template
- 代码没写错,渲染页面不显示原因
- MySQL(一)——安装
- YOLOv5增加小目标检测层
- 整型提升和大小端字节序
- Some habits of it veterans in the workplace
- Linux MySQL implements root user login without password
- ROS rviz_ Satellite function package visualizes GNSS track and uses satellite map
- AutoCAD C polyline small acute angle detection
- ThreadLocal
猜你喜欢

How to open UMD, KMD log and dump diagrams in CAMX architecture

JDBC学习(一)——实现简单的CRUD操作

Yygh-6-wechat login

Freeswitch uses origin to dialplan

mac下安装多个版本php并且进行管理

FPGA - 7系列 FPGA SelectIO -08- 高级逻辑资源之OSERDESE2

freeswitch使用mod_shout模块播放mp3

socke.io長連接實現推送、版本控制、實時活躍用戶量統計

Batch import of pictures into WPS table by date

Slow content advertising: the long-term principle of brand growth
随机推荐
Integer promotion and size side byte order
ThreadLocal
AutoCAD C# 多段線小銳角檢測
JDBC learning (I) -- implementing simple CRUD operations
【Paper Reading-3D Detection】Fully Convolutional One-Stage 3D Object Detection on LiDAR Range Images
socke.io长连接实现推送、版本控制、实时活跃用户量统计
Is it safe to open a stock account? How to open a stock account?
基本类型和包装类的区别
ImportError: cannot import name 'ensure_ dir_ Possible solutions for exists'
整型提升和大小端字节序
AutoCAD C# 多段线自相交检测
调接口事件API常用事件方法
重载,重写的区别,抽象类,接口的区别
Socket. Io long Connection Push, version Control, Real - Time Active user volume Statistics
Promotion intégrale et ordre des octets de fin de taille
Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance
API learning of OpenGL (2007) gltexcoordpointer
AutoCAD C polyline self intersection detection
链表(一)——移除链表元素
Idea automatically adds comments when creating classes