gpt4 book ai didi

java - 使用 Stream 将逗号分隔的字符串转换为数组

转载 作者:行者123 更新时间:2023-12-02 06:22:23 26 4
gpt4 key购买 nike

如何使用 Java 8 Stream 将 Java 逗号分隔为对象数组?

 public static void main(String[] args){
String INPUT =
"00:00:01,400-234-090\n" +
"00:00:01,701-080-080\n" +
"01:05:00,600-234-090";
System.out.println(new Solution().solution(INPUT));

}

最佳答案

您可以使用Java Stream执行如下:

Arrays.stream(csvString.split("\r?\n"))
.map(x -> x.split(","))
.map(Arrays::asList)
.map(PhoneCall::new) //Stream<PhoneCall>
.collect(Collectors.groupingBy(x -> x.phoneNumber)) //Map<String, List<PhoneCall>>
.values()
.stream()



private static class PhoneCall {
final String phoneNumber;
final int hours;
final int minutes;
final int seconds;


PhoneCall(List<String> values) {
phoneNumber = values.get(1);
String[] durationArray = values.get(0).split(":");
hours = Integer.valueOf(durationArray[0]);
minutes = Integer.valueOf(durationArray[1]);
seconds = Integer.valueOf(durationArray[2]);
}
}

关于java - 使用 Stream 将逗号分隔的字符串转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55822123/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com