使用 Guava 的 Splitter 效率更高。

使用 Guava 的 Splitter 可以直接将字符串按照指定的分隔符拆分成一个 Iterable 对象,然后可以使用 Stream API 将其转换成 Map。这样可以避免使用 lambda 表达式,减少了代码的复杂性,并且在处理大量数据时,Guava 的 Splitter 具有更好的性能。

以下是使用 Guava 的 Splitter 实现的代码示例:

import com.google.common.base.Splitter;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        String input = '100001|30,100002|45';
        
        Map<String, Integer> map = Splitter.on(',')
                .withKeyValueSeparator('|')
                .split(input)
                .entrySet()
                .stream()
                .collect(Collectors.toMap(Map.Entry::getKey, e -> Integer.parseInt(e.getValue())));
        
        System.out.println(map);
    }
}

输出结果为:{100001=30, 100002=45}


原文地址: https://www.cveoy.top/t/topic/pkL5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录