java - Search specific objects in ArrayList by attribute -
good day,
imagine have following code: (these not attributes)
class owner { private string name; } class car { private owner owner; private string brandname; public boolean isclean() { // not included in contructor return false; } class fuelcar extends car { private string fueltype; public boolean isclean() { if (fueltype.equals("diesel")){ return false; } else { return true; } } class electriccar extends car { private int batterylevel; public boolean isclean() { return true; } }
the objects added arraylist:
arraylist<car> cars = new arraylist<>();
examples:
cars.add(new auto("audi", new owner("peter"))); cars.add(new auto("fiat", new owner("rob"))); cars.add(new auto(mercedes, null)); cars.add(new electriccar(10, "opel ", new owner("unknown"))); cars.add(new electriccar(100,"google", new owner("google"))); cars.add(new fuelcar("diesel", "seat", new owner("tom"))); cars.add(new fuelcar("gasonline", "smart", new owner("marcel")));
now questions are:
how can make method list cars have value isclean "true";
how can make method following signature: public static void printcarsspecific(arraylist cars, string fueltype) example if put in: printcarsspecific("gasoline"); cars shown when printing arraylist.
ps: it's not homework. education typed code above myself , didnt copy , paste because become way large.
i tried these methods:
public static void printbedrijfsautosmettype(arraylist<auto> autos, string brandstof) { iterator<auto> iter = autos.iterator(); while (iter.hasnext()) { auto auto = iter.next(); if (auto instanceof brandstofauto) { string brandstof1 = ((brandstofauto) auto).getbrandstof(); if (!brandstof1.equals(brandstof) || brandstof1 == null) { iter.remove(); } } (int = 0; < autos.size(); i++) { system.out.println(autos.get(i)); } } }
and
public static void printschoneautos(arraylist<auto> autos) { iterator<auto> iter = autos.iterator(); while (iter.hasnext()) { auto auto = iter.next(); if (auto instanceof brandstofauto) { boolean isschoon = ((brandstofauto) auto).isschoon(); boolean isschoon3 = auto.isschoon(); if (isschoon3 == false || isschoon == false) { iter.remove(); } } (int = 0; < autos.size(); i++) { system.out.println(autos.get(i)); } } }
i guess don't have delete these items i've seen examples under here.
if using java 8 use fancy streams such :
list<car> cleancars = carlist.stream().filter(car -> car.isclean()).collect(collectors.tolist()); list<car> carsfilteredonfueltype = carlist.stream().filter(car -> fueltype.equals(car.fueltype)).collect(collectors.tolist));
Comments
Post a Comment