4
我想運行一個java程序中找到的java程序,我在java必要的步驟課程中找到。我想使用eclipse來通過它來更好地理解發生了什麼。 Person類沒有錯誤,但是MRTest類最後有一個錯誤,那就是stream()方法對於調用它的類型是未定義的。我不知道如何解決這個問題。「方法stream()未定義的類型設置<Person>」
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Collection;
import java.util.function.Supplier;
import java.util.Set;
import java.util.HashSet;
import java.time.chrono.IsoChronology;
public class MRTest {
// The method transferElements copies elements from one collection to
// another
public static <T, SOURCE extends Collection<T>, DEST extends Collection<T>>
DEST transferElements(
SOURCE sourceCollection,
Supplier<DEST> collectionFactory) {
DEST result = collectionFactory.get();
for (T t : sourceCollection) {
result.add(t);
}
return result;
}
public static void main(String... args) {
List<Person> roster = Person.createRoster();
for (Person p : roster) {
p.printPerson();
}
Person[] rosterAsArray =
roster.toArray(new Person[roster.size()]);
class PersonAgeComparator
implements Comparator<Person> {
public int compare(Person a, Person b) {
return a.getBirthday().compareTo(b.getBirthday());
}
}
// Without method reference
Arrays.sort(rosterAsArray, new PersonAgeComparator());
// With lambda expression
Arrays.sort(rosterAsArray,
(Person a, Person b) -> {
return a.getBirthday().compareTo(b.getBirthday());
}
);
// With method reference
Arrays.sort(rosterAsArray, Person::compareByAge);
// Reference to an instance method of a particular object
class ComparisonProvider {
public int compareByName(Person a,
Person b) {
return a.getName().compareTo(b.getName());
}
public int compareByAge(Person a,
Person b) {
return a.getBirthday().compareTo(b.getBirthday());
}
}
ComparisonProvider myComparisonProvider = new ComparisonProvider();
Arrays.sort(rosterAsArray, myComparisonProvider::compareByName);
// Reference to an instance method
// of an arbitrary object of a particular type
String[] stringArray = { "Barbara", "James", "Mary", "John",
"Patricia", "Robert", "Michael", "Linda" };
Arrays.sort(stringArray, String::compareToIgnoreCase);
Set<Person> rosterSetLambda =
transferElements(roster,() -> { return new HashSet<>(); });
Set<Person> rosterSet = transferElements(
roster, HashSet::new);
System.out.println("Printing rosterSet:");
rosterSet.stream().forEach(p -> p.printPerson()); // This is the line that is the problem.
}
}
什麼Java編譯器是你使用Eclipse? –
你有什麼版本的Java JDK?流被添加到8,所以你可能有一箇舊版本。 – resueman
eclipse luna 4.4,JRE8和java兼容級別1.8 –