[英]How to convert a String Array to a Long Array in a Java8 one-liner?
I'm solving the "Count Triplets" problem on HackerRank.我正在解决 HackerRank 上的“Count Triplets”问题。 https://www.hackerrank.com/challenges/count-triplets-1/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dictionaries-hashmaps It says that I must work with an array, although HC converts it to a List. https://www.hackerrank.com/challenges/count-triplets-1/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dictionaries-hashmaps它说我必须使用数组, 尽管 HC 将其转换为列表。 I want to convert in into an array instead of a list.我想转换成数组而不是列表。
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
String[] nr = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");
int n = Integer.parseInt(nr[0]);
long r = Long.parseLong(nr[1]);
**List<Long> arr = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
.map(Long::parseLong)
.collect(toList());**
long ans = countTriplets(arr, r);
bufferedWriter.write(String.valueOf(ans));
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
Do it as follows:执行以下操作:
Long[] arr = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
.map(Long::parseLong)
.collect(Collectors.toList())
.toArray(Long[]::new);
There is no need to collect into a List
as shown above.如上所示,无需收集到List
中。 You can do it simply as你可以简单地做到这一点
Long[] arr = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
.map(Long::parseLong)
.toArray(Long[]::new);
Alternatively,或者,
long[] arr = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
.mapToLong(Long::parseLong)
.toArray()
Use .toArray(Long[]::new)
instead of .collect(Collectors.toList())
使用.toArray(Long[]::new)
而不是.collect(Collectors.toList())
Long[] arr = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
.map(Long::parseLong)
.toArray(Long[]::new);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.