Learning lambda expressions encountered in the pit

A recent study using java8 lambda expressions. According to the literal meaning of the method, it is easy to understand and use to get started.

But recently encountered when using a lambda expression problem, code logic without any problems, but the result is not satisfactory.

First the old code:

testOneList.stream().distinct().filter(item ->

  !testTowList.stream().map(TestTwoModel::getCode).collect(Collectors.toList()).contains(item)

).map(item -> testTwoList.add(new TestTwoModel(item,.....)));

I began to wonder if I am using the wrong method, so do not use this method? Yeah unreasonable. Search the Internet for a long time, continuous testing and commissioning, we did not find the problem.

 

Finally, request the great God, we will see to the mistake. Read:

testOneList.stream().distinct().filter(item ->

  !testTowList.stream().map(TestTwoModel::getCode).collect(Collectors.toList()).contains(item)

).forEach(item -> testTwoList.add(new TestTwoModel(item,.....)));

 

map itself is not an end point, placed at the end it will be ignored, and we wanted to change forEach or later add collect will work.

Guess you like

Origin www.cnblogs.com/tu-emily/p/11820731.html