2017-10-08 15 views
-5

下面类中除去的lambda我有如下所示其使用Stream S中的下面的java类。我有一个名为person的基本班级,然后还有其他班级,我正在使用Stream s。从在Java

有没有办法通过它我可以避开lambda表达式并删除它们?

public class StreamMapDemo 
{ 
    public static void main(String[] args) 
    { 
     List<Person> personList = new ArrayList<>(); 

     personList.add(new Person("Alice", "[email protected]", Gender.FEMALE, 16)); 
     personList.add(new Person("Bob", "[email protected]", Gender.MALE, 15)); 
     personList.add(new Person("Carol", "[email protected]", Gender.FEMALE, 23)); 
     personList.add(new Person("David", "[email protected]", Gender.MALE, 19)); 
     personList.add(new Person("Eric", "[email protected]", Gender.MALE, 26)); 

     personList.stream()      // Stream<Person> 
        .map(p -> p.getEmail())  // Stream<String> 
        .forEach(System.out::println); 

     System.out.println("\n----------------------\n"); 

     personList.stream() // Stream<Person> 
        .map(p -> p.getName().toUpperCase()) // Stream<String> 
        .forEach(System.out::println); 

     System.out.println("\n----------------------\n"); 

     personList.stream() // Stream<Person> 
        .mapToInt(p -> p.getAge()) //IntStream 
        .forEach(age -> System.out.println(age)); 

    } 

} 

输出

[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 

---------------------- 

ALICE 
BOB 
CAROL 
DAVID 
ERIC 

---------------------- 

16 
15 
23 
19 
26 
+4

使用常规循环转换的代码。 –

+1

删除lamda或流? – azro

+3

如果您说*为什么要删除lambda表达式可能会有所帮助。这里有些人不清楚,如果你想删除只是lambda或流。而且人们不得不想知道lambda表达式有什么问题。 – RealSkeptic

回答

1

您可以使用方法引用来代替lambda表达式:

personList.stream()      
    .map(Person::getEmail)   
    .forEach(System.out::println); 

personList.stream() 
    .map(Person::getName) 
    .map(String::toUpperCase) 
    .forEach(System.out::println); 

personList.stream() 
    .mapToInt(Person::getAge) 
    .forEach(System.out::println); 
+0

我不确定OP是否也想避免**流**。但如果不是,那么这可能确实是他正在寻找的替代方案。绝对看起来更清楚。 – Zabuza

0

如果你还不想使用,这里是一个版本使用定期循环昔日

for (final Person person : personList) { 
    System.out.println(person.getEmail()); 
} 

System.out.println("\n----------------------\n"); 

for (final Person person : personList) { 
    System.out.println(person.getName().toUpperCase()); 
} 

System.out.println("\n----------------------\n"); 

for (final Person person : personList) { 
    System.out.println(person.getAge()); 
} 

或一起,如果你被人要组:

for (final Person person : personList) { 
    System.out.println(person.getEmail()); 
    System.out.println(person.getName().toUpperCase()); 
    System.out.println(person.getAge()); 
    System.out.println("----------------------"); 
} 

需要注意的是这个版本稍微改变输出。然而它更快,你只需要一次迭代而不是三次。然后

的输出是这样的:

[email protected] 
ALICE 
16 
---------------------- 
[email protected] 
BOB 
15