优雅的使用for循环
java 两层嵌套循环可以用Map 进行优化
:循环数据越小,两者差别也就越小,但是数据量越大,差别也就越大
class Member {
private Integer id;
private String name;
private Integer age;
private Date addDate;
}
不使用map
int forNumber = 0;
for(Member m2:list2){
if(m2.getName()==null){
for(Member m1:list1){
if(m1.getId().intValue()==m2.getId().intValue()){
forNumber++;
}
}
}
}
使用Map
int mapNumber = 0;
Map<Integer, Member> map = new HashMap<>();
for(Member m1:list1){
map.put(m1.getId(), m1);
}
for(Member m2:list2){
if(m2.getName()==null){
Member m = map.get(m2.getId());
if(m!=null){
mapNumber++;
}
}
}
如果在本地跑上面的两个遍历方式的话,便会得出结论:循环数据越小,两者差别也就越小,但是数据量越大,差别也就越大
,所以双层for循环还是使用Map比较好
使用for循环的一些规则:
-
循环嵌套外小内大原则
for (int i = 0; i < 10; i++){ for (int j = 0; j < 1000; j++){ } }
-
异常处理写在循环外面
try { for (int i = 0; i < 10; i++){ } } catch (Exception e){ }
-
循环嵌套提取不需要循环的逻辑
// 错误示范
int a = 10, b =11;
int x = 0;
for(int i = 0; i < 10; i++){
x = a * b * i;
}
// 正确示范
int a = 10, b =11;
int x = a * b;
for(int i = 0; i < 10; i++){
x = x * i;
}
优雅的使用if判断
使用 Map
if (t == 1) {
type = "name";
} else if (t == 2) {
type = "id";
} else if (t == 3) {
type = "mobile";
}
优化
Map<Integer, String> typeMap = new HashMap<>();
typeMap.put(1, "name");
typeMap.put(2, "id");
typeMap.put(3, "mobile");
// 判断语句
type = typeMap.get(t);
利用include做判断
// bad
if (age === 10 || age === 20 || age === 30 || age === 40) {
test();
}
// good
const ages = [10, 20, 30, 40];
if (ages.include(age)) {
test();
}
判断区间
例如:判断一个数字在某个区间(比如:0~360),分成8等份,分别是 0-45、46-90、91-135 等等依次类推。
// bad
if (degree < 45) {
} else if (degree < 90) {
} else if (degree < 135) {
// 一直到360
}
// good
// 优雅的判断一个数在某个区间0~360分八份
const rangeMap = {
A: function () {
console.log("0-45");
},
B: function () {
console.log("45-90");
},
C: function () {
console.log("90-135");
},
// more...
};
// 建立映射关系
const angleArray = ["A", "B", "C", "D", "E", "F", "G", "H"];
const range = [45, 90, 135, 180, 225, 270, 315, 360];
const getAngleMap = (num) => {
for (let i = 0; i < range.length; i++) {
if (num <= range[i]) {
return angleArray[i];
}
}
};
// 函数调用
rangeMap[getAngleMap(65)](); // 45-90
合并条件表达式(||)
String city = "西安";
String area = "029";
String province = "陕西";
if ("西安".equals(city)) {
return "xi'an";
}
if ("029".equals(area)) {
return "xi'an";
}
if ("陕西".equals(province)){
return "xi'an";
}
优化
if ("西安".equals(city) || "029".equals(area) || "陕西".equals(province)){
return "xi'an";
}
优化判断逻辑
// 年龄大于 18
if (age > 18) {
// 工资大于 5000
if (salary > 5000) {
// 是否合格
if (flag== true) {
return true;
}
}
}
return false;
优化
if (age < 18) {
return false;
}
if (salary < 5000) {
return false;
}
return flag;
三元运算符
score = score > 80 ? 100 : 60;