Omegaspard
Omegaspard

Reputation: 1980

Convert a stream into a list

I want to convert a stream into a list. To do so I have tried this code :

try(Stream<String> stream = Files.lines(Paths.get(args[0]))) {
    List<String> lines =  stream.collect(Collectors.toList());
}

But then the compiler tell me that :

Type mismatch: cannot convert from List<Object> to List<String>

Also I've tried this way :

try(Stream<String> stream = Files.lines(Paths.get(args[0]))) {
    List<String> lines =  Stream.of(stream).collect(Collectors.toList());
}

But then I have this error :

This static method of interface Stream can only be accessed as Stream.of

which happen every time, whenever I use the Stream.of methods.

Can someone help me out, please?

Upvotes: 2

Views: 1548

Answers (1)

qwazer
qwazer

Reputation: 7531

It's seems that you use java compiler language level lower than 8. Try compiling from command line with

javac -source 8

Also check your language level project setting in IDE.

For example, output from IDEA 2016 hides info about used language level, but provide info about javac version

  Information:Using javac 1.8.0_101 to compile java sources
    Information:java: Errors occurred while compiling module 'demo_04'
    Information:8/1/16 2:13 PM - Compilation completed with 1 error and 0 warnings in 1s 403ms
    /tmp/1/src/JavaStreamExample.java
    Error:(16, 49) java: incompatible types: java.util.List<java.lang.Object> cannot be converted to java.util.List<java.lang.String>

Upvotes: 1

Related Questions