+ 1

Why does this code cause the error "The method toList() is undefined for the type Copy" and how do I solve this?

List<Path> sources = Files.walk(from).collect(toList()); I'm trying to copy a folder with all the files and subfolders in it WITHOUT using external libraries. So you can suggest any other methods, too. (Java 8) "from" is the source of the files. (I'm new to Java)

28th Aug 2019, 2:15 PM
Tashila Pathum
Tashila Pathum - avatar
3 odpowiedzi
+ 3
Ok, so you’re new to Java so apologies if I explain this in detail you already know: If we look up the method you are trying to use - toList() - we can see that the method definition for it (e.g its return type, parameters, etc) says it is a static method https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html Static methods mean they are not called by an instance of a class. For example, say I have a class Person. I might have a method in the Person class public String getName() {...} that gets the name of my created object of an instance of Person Person p = new Person(); String name = p.getName(); I am able to call getName() using my instance of Person, object p. Say I defined a static method getType() for the class Person public static String getType() { return “Human”; } Notice I will not be able to call getType() with an instance of Person because the static method has nothing to do with instances created of the class. e.g Person p = new Person(); String type = p.getType(); //compilation error String type = Person.getType(); To use the static method, I need to refer to the class it comes from. Hence why toList() must be called as Collectors.toList() Your error implies you are in a class called ‘Copy’ and as you were calling toList() on its own - i.e. not from an instance of a class or not statically from the Collectors class - whilst compiling, there is a search to find a toList() method defined in the class you are already in. I hope that helps!
31st Aug 2019, 1:10 PM
Jenine
+ 3
Glad to hear Tashila :)
1st Sep 2019, 8:25 AM
Jenine
+ 1
Jenine Thank you! You solved my problem and explained it perfectly.
1st Sep 2019, 8:08 AM
Tashila Pathum
Tashila Pathum - avatar