简体   繁体   English

将字符串流转换为 Longs 流

[英]Convert stream of Strings to stream of Longs

I have a List<String> that I would like converted to a List<Long> .我有一个List<String> ,我想将其转换为List<Long> Before Java 8, I would do this by looping through the List<String> , converting each String to a Long and adding it to the new List<Long> , as shown below.在 Java 8 之前,我会通过循环遍历List<String>来完成此操作,将每个String转换为Long并将其添加到新的List<Long> ,如下所示。

List<String> strings = /* get list of strings */;
List<Long> longs = new ArrayList<>();
for (final String string : strings) {
    longs.add(Long.valueOf(string));
}

However, I need to do this conversion using Java 8 streams, as the conversion is part of a larger stream operation.但是,我需要使用 Java 8 流进行此转换,因为转换是较大流操作的一部分。 I have the List<String> as a stream, as if I had done strings.stream() .我将List<String>作为流,就像我已经完成了strings.stream() So, how could I perform this conversion, similar to something like this.那么,我怎么能执行这种转换,类似于这样的事情。

List<String> strings = /* get list of strings */;
List<Long> longs = strings.stream().map(/*convert to long*/).collect(Collectors.toList());

Solution was very simple.解决方案非常简单。 Just needed to use Long::valueOf .只需要使用Long::valueOf

List<Long> longs = strings.stream().map(Long::valueOf).collect(Collectors.toList());

OR Long::parseLongLong::parseLong

List<Long> longs = strings.stream().map(Long::parseLong).collect(Collectors.toList());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM