最大限度地减少此代码并消除需要使用元素数组从forEach
内部为变量分配值的最佳方法是什么:
@Override
public List<User> getModel() {
List<User> usersModel = new LinkedList<User>();
IntStream.of(getWidgetCount()).forEach(i -> {
Widget widget = getWidget(i);
AuthManagerRow row = (AuthManagerRow) widget;
User widgetModel = row.getModel();
final Boolean[] contains = {false};
usersModel.forEach(user -> {
if(user.getObjectId().equals(widgetModel.getObjectId())) {
contains[0] = true;
}
});
if(!contains[0]) {
usersModel.add(widgetModel);
}
});
return usersModel;
}
答案 0 :(得分:2)
Map<Integer, User> users = new HashMap<>();
IntStream.of(getWidgetCount())
.mapToObject(i -> ((AuthManagerRow) getWidget(i)).getModel())
.forEach(model -> users.putIfAbsent(model.getObjectId(), model));
return new ArrayList<>(users.values());
假设User.getObjectId()
返回Integer
。