简体   繁体   中英

Java 8 Lambda Consuming using numerous times a piece of information with one iteration

I build a small example to test the java 8. Having a list of Strings:

List<String> list = Arrays.asList(new String[] { "Sheep", "Ship","Skeleton" });

The following function:

list.stream().forEach(name -> list.forEach(name2->System.out.println("Name2:"+name2+" name:" + name + "=>" + name2.compareTo(name))));

returns the comparison between name2 and name1.

I am trying to test and I don't know if it is feasible this scenario: Having the same list and an independent String variable called lastFoundWord can I assign with a "lambda way" the variable just right after the comparison as it happens with the previous line ?

Note :I see that forEach can not accept a list of Consumers, and Consumer building is very strict. I am not sure about the "Function" interface. All my thought directs me to iterate twice the same information.

Is there perhaps a forEach function that accepts a list of Consumers and I missed it ?

Using consumers from a list is something I try to figure.

Although for my current example, I found a solution using braces. So the code turned to that:

list.stream().forEach(name -> list.forEach(name2 -> {
    System.out.println("Name2:" + name2 + " name:" + name + "=>" + name2.compareTo(name));
    lastName = name2;
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM