Issue
I am trying to filter my Deals
based on my Deal
options but when I try to filter the code I get a type mismatch error that Set<DealOptions>
cannot be converted to boolean. I want to keep the deals when all the deal options are red.
Here is my code:
import java.util.*;
import java.util.stream.Collectors;
class Deal {
String dealname;
String dealprice;
Set<DealOptions> dealop;
public String getDealname() {
return dealname;
}
public void setDealname(String dealname) {
this.dealname = dealname;
}
public String getDealprice() {
return dealprice;
}
public void setDealprice(String dealprice) {
this.dealprice = dealprice;
}
public Set<DealOptions> getDealop() {
return dealop;
}
public void setDealop(Set<DealOptions> dealop) {
this.dealop = dealop;
}
}
class DealOptions {
String optname;
String color;
public String getOptname() {
return optname;
}
public void setOptname(String optname) {
this.optname = optname;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
public class Test {
public static void main(String[] args)
{
Deal s = new Deal();
Set<DealOptions> ops = new HashSet<DealOptions>();
DealOptions op = new DealOptions();
s.setDealname("mongo");
s.setDealprice("500");
op = new DealOptions();
op.setColor("red");
op.setOptname("redop");
ops.add(op);
op = new DealOptions();
op.setColor("blue");
op.setOptname("blueop");
ops.add(op);
op = new DealOptions();
op.setColor("green");
op.setOptname("greenop");
ops.add(op);
s.setDealop(ops);
List<Deal> dl = new ArrayList<Deal>();
dl.add(s);
ops = new HashSet<DealOptions>();
s = new Deal();
op = new DealOptions();
s.setDealname("test2");
s.setDealprice("200");
op = new DealOptions();
op.setColor("indigo");
op.setOptname("indigop");
ops.add(op);
op = new DealOptions();
op.setColor("violet");
op.setOptname("violetop");
ops.add(op);
op = new DealOptions();
op.setColor("orange");
op.setOptname("orangeop");
ops.add(op);
s.setDealop(ops);
dl.add(s);
List<Deal> dev = dl.stream().filter(
(p) -> p.getDealop().stream().filter((po) -> po.getColor().equals("red")).collect(Collectors.toSet()))
.collect(Collectors.toList()); // error here
}
}
Error:
Cannot convert from Set to boolean
How do rectify this error how can I filter my deals based on my deal options?
Solution
You can use allMatch(predicate)
to determine if all deals of an option are red:
Returns whether all elements of this stream match the provided predicate.
In this case, the predicate simply tells whether an option is red or not.
List<Deal> output =
dl.stream()
.filter(d -> d.getDealop().stream().allMatch(po -> po.getColor().equals("red")))
.collect(Collectors.toList());
Answered By - Tunaki Answer Checked By - Katrina (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.