随手记2025-10-28

目录

1、使用三元表达式

2、for-each 语句

3、利用try-with-resource 语句

4、利用lambda 表达式

5、利用方法引用

6、利用泛型

7、判断条件优化

8、合理选用switch...case...和if...else...

9、数据初始化

10、BeanUtils.copyProperties代替挨个赋值

11、stream流

12、使用枚举


开发技巧

1、使用三元表达式

String title;
if (isMember(phone)) {
    title = "会员";
} else {
    title = "游客";
}

替换为:
String title = isMember(phone) ? "会员" : "游客";

2、for-each 语句

double[] values = ...;
	for(int i = 0; i < values.length; i++) {
        double value = values[i];    
        // TODO: 处理value
    }
 
List<Double> valueList = ...;
Iterator<Double> iterator = valueList.iterator();
 
while (iterator.hasNext()) {
    Double value = iterator.next();    
    // TODO: 处理value
}

替换为:
double[] values = ...;
for(double value : values) {    
    // TODO: 处理value
}
List<Double> valueList = ...;
for(Double value : valueList) {
    // TODO: 处理value
}

3、利用try-with-resource 语句

所有实现 Closeable 接口的“资源”,均可采用 try-with-resource 进行简化。

BufferedReader reader = null;
try {
    reader = new BufferedReader(new FileReader("cities.csv"));
    String line;
    while ((line = reader.readLine()) != null) {
        // TODO: 处理line
    }
} catch (IOException e) {
    log.error("读取文件异常", e);
} finally {
    if (reader != null) {
        try {
            reader.close();
        } catch (IOException e) {
            log.error("关闭文件异常", e);
        }
    }
}

替换为:
try (BufferedReader reader = new BufferedReader(new FileReader("test.txt"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        // TODO: 处理line
    }
} catch (IOException e) {
    log.error("读取文件异常", e);
}

4、利用lambda 表达式

new Thread(new Runnable() {
    public void run() {
        // 线程处理代码
    }
}).start();

替换为
new Thread(() -> {
    // 线程处理代码
}).start();

5、利用方法引用

方法引用(::),可以简化 lambda 表达式,省略变量声明和函数调用。stream流中用的多

Arrays.sort(nameArray, (a, b) -> a.compareToIgnoreCase(b));
 
List<Long> userIdList = userList.stream()
    .map(user -> user.getId())
    .collect(Collectors.toList());

简化:
Arrays.sort(nameArray, String::compareToIgnoreCase);
 
List<Long> userIdList = userList.stream()
    .map(UserDO::getId)
    .collect(Collectors.toList());

6、利用泛型

7、判断条件优化

double result;
if (value <= MIN_LIMIT) {
    result = MIN_LIMIT;}
else {
    result = value;
}

简化为:
double result = Math.max(MIN_LIMIT, value);

8、合理选用switch...case...和if...else...

9、数据初始化

public static final List<String> ANIMAL_LIST;
static {
    List<String> animalList = new ArrayList<>();
    animalList.add("dog");
    animalList.add("cat");
    animalList.add("tiger");
    ANIMAL_LIST = Collections.unmodifiableList(animalList);
}


简化为:

public static final List<String> ANIMAL_LIST = Arrays.asList("dog", "cat", "tiger");

10、BeanUtils.copyProperties代替挨个赋值

11、stream流

12、使用枚举

if (score > 500 && score <= 1000) {
	tabStaDeptViolationCount.setRangeAbove("1");
}


替换为

@Getter
public enum RangeAboveEnum {
    RANGE_1(1, 0, 500, "0~500"),
    RANGE_2(2, 500, 1000, "500~1000");

    RangeAboveEnum(Integer val, Integer startNum, Integer endNum, String des) {
        this.val = val;
        this.startNum = startNum;
        this.endNum = endNum;
        this.des = des;
    }

    /**
     * 值
     */
    private Integer val;

    /**
     * 起始分数
     */
    private Integer startNum;

    /**
     * 结束分数
     */
    private Integer endNum;
    /**
     * 描述
     */
    private String des;
}


if (score <= RangeAboveEnum.RANGE_1.getStartNum()) {
	tabStaDeptViolationCount.setRangeAbove(RangeAboveEnum.RANGE_1.getVal());
}

摘自:https://blog.youkuaiyun.com/z1ztai/article/details/148256712?spm=1001.2014.3001.5502

侵删

    评论
    成就一亿技术人!
    拼手气红包6.0元
    还能输入1000个字符
     
    红包 添加红包
    表情包 插入表情
     条评论被折叠 查看
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

    当前余额3.43前往充值 >
    需支付:10.00
    成就一亿技术人!
    领取后你会自动成为博主和红包主的粉丝 规则
    hope_wisdom
    发出的红包
    实付
    使用余额支付
    点击重新获取
    扫码支付
    钱包余额 0

    抵扣说明:

    1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
    2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

    余额充值