简体   繁体   中英

How to collect X type objects from a stream, that contain only some fields of the same X type object, without using an auxiliary collection

An example:

This permits to extract one field

Collection<X> base=...;
List<?> c=base.stream().map(->i.getField()).distinct.collect(Collectors.toList()));

This requires an auxiliary collection

Collection<X> fromBase; //empty collection
Collection<X> base=...;
List<?> c=base.stream().forEach(i->{
    X k=...; //create object X with some fields
    fromBase.add(k);
});

There is a way to extract more fields, like with .map(), directly ?

Basic example:

List<X> lst;

private void collectDistinctItems(){
    lst = new ArrayList<>();
    getSomeItems().stream().forEach(i->{  //Collection<X>
        X tmp=new X();
        tmp.setField1(i.getField1());  //copy some fields
        tmp.setField2(i.getField2());
        tmp.setField3(i.getField3());
        ...

        if(!lst.contains(tmp)) lst.add(tmp); //add new X item to X type list
    });
}

A first step would be to use a collector:

lst = getSomeItems().stream().map(i->{  //Collection<X>
      X tmp=new X();
      tmp.setField1(i.getField1());  //copy some fields
      tmp.setField2(i.getField2());
      tmp.setField3(i.getField3());
      return tmp; })
    .distinct()
    .collect(toList());

You could also extract the copy into a separate method:

private static X copy(X original) {
    X tmp=new X();
    tmp.setField1(i.getField1());  //copy some fields
    tmp.setField2(i.getField2());
    tmp.setField3(i.getField3());
    return tmp;
}

and use a method reference:

lst = getSomeItems().stream()
    .map(MyClass::copy)
    .distinct()
    .collect(toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM