java8:处理数据stream并传值
以下是可以将百分比的值直接塞入实体类的方法:
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
class Entity {
String name;
int pid;
long time;
long lastTime;
double percentage;
public Entity(String name, int pid, long time) {
this.name = name;
this.pid = pid;
this.time = time;
}
}
public class Main {
public static List<Entity> calculatePercentage(List<Entity> beforeList, List<Entity> afterList, long duringTime) {
return beforeList.stream()
.map(beforeEntity -> {
Entity afterEntity = afterList.stream()
.filter(a -> a.pid == beforeEntity.pid)
.findFirst()
.orElse(null);
if (afterEntity!= null) {
long lastTime = afterEntity.time - beforeEntity.time;
double percentage = (double) lastTime / duringTime;
beforeEntity.lastTime = lastTime;
beforeEntity.percentage = percentage;
}
return beforeEntity;
})
.collect(Collectors.toList());
}
public static void main(String[] args) {
List<Entity> before = new ArrayList<>();
before.add(new Entity("item1", 1, 1000));
before.add(new Entity("item2", 2, 2000));
List<Entity> after = new ArrayList<>();
after.add(new Entity("item3", 1, 1500));
after.add(new Entity("item4", 2, 2500));
List<Entity> result = calculatePercentage(before, after, 1000);
result.forEach(System.out::println);
}
}