You can't use a method reference, since you have no way of passing the int argument to it.
Therefore, use a lambda expression instead:
lines.forEach(s -> chunker.splitFileByMaxRows(s,someInt));
Answer from Eran on Stack OverflowYou can't use a method reference, since you have no way of passing the int argument to it.
Therefore, use a lambda expression instead:
lines.forEach(s -> chunker.splitFileByMaxRows(s,someInt));
A MethodReference can be used only in the place where a Consumer is allowed. If you recollect a Consumer takes in only one input parameter. So in your case you have two arguments, this is not possible to be passed in as Method reference to a consumer. So you have to use a lambda that can take arguments as necesssary.
you could just use a forEach:
listModel.forEach(model -> {
try {
new UpDateData().bankData(model.getCust_id(), model.getBank_id(), model.getDate());
} catch(){
.... handle
}
})
The forEach is used in java 8 for iteration.You can loop over all elements using Iterable.forEach() method.
List<String> words = new ArrayList<>(Arrays.asList("the", "this",
"that", "there"));
alphabets.forEach(s -> { System.out.println(s) }); //using lamda
The List<> is the iteratable type, so you can directly use forEach on list.This is known as internal iteration as compared to old external iteration. This is automatically converted to external iteration by java. Curly braces are optional in lambda if there is only one statement else mandatory. You can use filter on iterators as compared to old if blocks in loops.
alphabets.stream()
.filter(s -> s.startsWith("the"))
.forEach(System.out::println);
alphabets.stream()
.filter(s -> s.length() > 3)
.forEach(System.out::println);
The above syntax use method reference for printing the elements.
https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html
WARNING
As mentioned in comments, Using peek() for production code is considered bad practice
The reasson is that "According to its JavaDocs, the intermediate Stream operation java.util.Stream.peek() “exists mainly to support debugging” purposes."
As a consequence, this proposed solution SHOULD NOT be used.
Forgot to relate to the first code snippet. I wouldn't use forEach at all. Since you are collecting the elements of the Stream into a List, it would make more sense to end the Stream processing with collect. Then you would need peek in order to set the ID.
List<Entry> updatedEntries =
entryList.stream()
.peek(e -> e.setTempId(tempId))
.collect (Collectors.toList());
For the second snippet, forEach can execute multiple expressions, just like any lambda expression can :
entryList.forEach(entry -> {
if(entry.getA() == null){
printA();
}
if(entry.getB() == null){
printB();
}
if(entry.getC() == null){
printC();
}
});
However (looking at your commented attempt), you can't use filter in this scenario, since you will only process some of the entries (for example, the entries for which entry.getA() == null) if you do.
List<String> items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
items.add("D");
items.add("E");
//lambda
//Output : A,B,C,D,E
items.forEach(item->System.out.println(item));
//Output : C
items.forEach(item->{
System.out.println(item);
System.out.println(item.toLowerCase());
}
});
Move your try/catch inside the loop?
items.forEach(item -> {
try {
getData(item);
} catch (Exception e) {
e.printStackTrace();
}
});
You can put try catch inside getData method at the block of code where exception may occur so in this case it will continue loop for others items if any exception occured:
public static void getData(String item) {
try {
System.out.println("====getData method called" + item + "====");
if (item.equals("1")) {
System.out.println(1 / 0);
}
} catch (Exception e) {
System.out.println("Exception at item: " + item);
e.printStackTrace();
}
}
There are three kinds of method references that can be used when a single value is available from the stream:
A parameter-less method of the streamed object.
class Observer { public void act() { // code here } } observers.forEach(Observer::act); observers.forEach(obs -> obs.act()); // equivalent lambdaThe streamed object becomes the
thisobject of the method.A static method with the streamed object as parameter.
class Other { public static void act(Observer o) { // code here } } observers.forEach(Other::act); observers.forEach(obs -> Other.act(obs)); // equivalent lambdaA non-static method with the streamed object as parameter.
class Other { void act(Observer o); } Other other = new Other(); observers.forEach(other::act); observers.forEach(obs -> other.act(obs)); // equivalent lambda
There is also a constructor reference, but that is not really relevant to this question.
Since you have an external value temp, and you want to use a method reference, you can do the third option:
class Temp {
private final BigDecimal temp;
public Temp(BigDecimal temp) {
this.temp = temp;
}
public void apply(TemperatureObserver observer) {
observer.react(this.temp);
}
}
Temp tempObj = new Temp(temp);
observers.forEach(tempObj::apply);
Take a look at the Method References section in the Java Tutorial. There it says:
There are four kinds of method references:
Reference to a static method:
ContainingClass::staticMethodNameReference to an instance method of a particular object:
containingObject::instanceMethodNameReference to an instance method of an arbitrary object of a particular type:
ContainingType::methodNameReference to a constructor:
ClassName::new
There it explains that i.e. TemperatureObserver::react would be a method reference of the 3rd type: a reference to an instance method of an arbitrary object of a particular type. In the context of your call to the Stream.forEach method, that method reference would be equivalent to the following lambda expression:
(TemperatureObserver item) -> item.react()
Or just:
item -> item.react()
Which doesn't match your void TemperatureObserver.react(BigDecimal t) method signature.
As you already suspect, there are cases for which you can't find an equivalent method reference for a lambda. Lambdas are way more flexible, though IMHO sometimes they are less readable than method references (but this is a matter of taste, many people think the other way round).
A way to still use a method reference would be with a helper method:
public static <T, U> Consumer<? super T> consumingParam(
BiConsumer<? super T, ? super U> biConsumer,
U param) {
return t -> biConsumer.accept(t, param);
}
Which you could use as follows:
observers.forEach(consumingParam(TemperatureObserver::react, temp));
But, honestly, I prefer to use a lambda.
java.util.Properties extends Hashtable<Object,Object>.
Therefore you'll have to cast the key and value to String in order to call your method (assuming all the keys and values are actually Strings) :
properties.forEach( (key, value) -> this.addOption((String) key, (String) value));
The alternative is to change the signature of your method to :
public void addOption(Object key, Object value)
You should cast key and value to String:
properties.forEach( (key, value) -> this.addOption((String)key, (String) value));
And why don't you use Map<String,String> to gain advantages of Generic
To iterate on a section of the original list, use the subList method:
list.subList(1, list.length()-1)
.stream() // This line is optional since List already has a foreach method taking a Consumer as parameter
.forEach(...);
This is the concept of streams. After one operation, the results of that operation become the input for the next.
So for your specific example, you can follow @Joni's command. But if you're asking in general, then you can create a filter to only get the values you want to loop over.
For example, if you only wanted to print the even numbers, you could create a filter on the streams before you forEached them. Like this:
List<Integer> intList = Arrays.asList(1,2,3,4,5);
intList.stream()
.filter(e -> (e & 1) == 0)
.forEach(System.out::println);
You can similarly pick out the stuff you want to loop over before reaching your terminal operation (in your case the forEach) on the stream. I suggest you read this stream tutorial to get a better idea of how they work: http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/