当前位置:网站首页>普歌 -- 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; // 返回最末的值
}
完结
边栏推荐
- Freeswitch使用originate转dialplan
- death_ satan/hyperf-validate
- How to open UMD, KMD log and dump diagrams in CAMX architecture
- Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
- Online facing such an online world, the only limitation is our imagination
- JS of learning notes -- split(), replace(), join()
- 阿里云短信服务(完整指南),短信发送功能实现。
- 调接口事件API常用事件方法
- JDBC learning (I) -- implementing simple CRUD operations
- [staff] arpeggio mark
猜你喜欢

D3D11_ Chili_ Tutorial (3): design a bindable/drawable system

Triode driven brushless motor

freeswitch设置最大呼叫时长

Exception handling (I) -- null pointer and array index out of bounds

AutoCAD C polyline self intersection detection

JDBC learning (I) -- implementing simple CRUD operations

Working principle of es9023 audio decoding chip

Socket. Io long Connection Push, version Control, Real - Time Active user volume Statistics

借助nz-pagination中的let-total解析ng-template

FPGA - 7 Series FPGA selectio -09- io of advanced logic resources_ FIFO
随机推荐
Drop down list processing in Web Automation
FPGA - 7 Series FPGA selectio -08- oserdese2 of advanced logic resources
VM332 WAService.js:2 Error: _vm.changeTabs is not a function报错
借助nz-pagination中的let-total解析ng-template
浮动与定位
选拔赛题目代码
[staff] arpeggio mark
socke.io长连接实现推送、版本控制、实时活跃用户量统计
调接口事件API常用事件方法
代码没写错,渲染页面不显示原因
ImportError: cannot import name 'ensure_dir_exists'的可解决办法
Yygh-7-user management
FPGA - 7 Series FPGA selectio -07- iserdese2 of advanced logic resources
fpm工具安装
Differences between overloads, rewrites, abstract classes and interfaces
JDBC学习(一)——实现简单的CRUD操作
Yolov5 adds a small target detection layer
death_ satan/hyperf-validate
API learning of OpenGL (2006) glclientactivetexture
CAD secondary development +nettopologysuite+pgis reference multi version DLL