arraylist - Java List, Counting non-zero attributes of Object, by group of 3 -
i have arraylist<fileline> , inside fileline function
public double getvalue() { ... doing stuff ... return value; } what i'm trying return count of non-zero getvalue() of group of 3 filelines.
let's have list<fileline> filelines of filelines.size() = 12 , respective getvalue() 0,0,0, 0,1,2, 0,3,0, 4,5,5 result i'd 3, valid expect first group.
if group of 1 fileline filter , count :
long resultcount = filelines.stream().filter(x -> x.getvalue() > 0).count(); , fact it's group of 3 causing me problem.
is best approach split list multiple 3 elements sublists or more elegant way?
you can group 3 mapping range of indices sublists this:
list<fileline> filtered = intstream.range(0, list.size()/3) .maptoobj(n -> list.sublist(n*3, n*3+3)) .filter(sublist -> sublist.stream().anymatch(fl -> fl.getvalue() != 0.0)) .flatmap(list::stream) .collect(collectors.tolist()); i assume want flatten groups back, added flatmap step. alternatively can leave them grouped if it's better in case:
list<list<fileline>> filtered = intstream.range(0, list.size()/3) .maptoobj(n -> list.sublist(n*3, n*3+3)) .filter(sublist -> sublist.stream().anymatch(fl -> fl.getvalue() != 0.0)) .collect(collectors.tolist()); if need count such groups, replace collect step count , merge map , filter single step:
long count = intstream.range(0, list.size()/3) .filter(n -> list.sublist(n*3, n*3+3).stream().anymatch(fl -> fl.getvalue() != 0.0)) .count();
Comments
Post a Comment