'stream every records based on filter and put them in list of errors

I am new to Java streams. I need to iterate over a list of objects and populate my list of errors based on my comparisons. I want to avoid using if else and use java stream. Is there a way I can do this?

public void compare(List<Tool> tools,Tool temp,List<String> error){
for(Tool t : tools){
   if(!t.name.equals(temp.name() && !t.id.equals(temp.id())
    errors.add(name+id+"not matches");
   if(!t.name.equals(temp.name())
    errors.add(name+"not matches");
   else if(!t.id.equals(temp.id())
    errors.add(id+"not matched");
}

class Tool{
  String name;
  String id;
}


Solution 1:[1]

The filter is id or name being different. All error messages can be constructed using 1 expression by using ternaries, so you can map non matching tools to a message in one step:

public void compare(List<Tool> tools, Tool temp, List<String> error) {
    tools.stream()
      .filter(t -> !t.id.equals(tool.id) || !t.name.equals(tool.name))
      .map(t -> (t.name.equals(tool.name) ? "" : name) + (t.id.equals(tool.id) ? "" : id) + "not matches")
      .forEach(error::add);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1