不使用元素数组从`forEach`中分配值

时间:2018-11-14 23:53:56

标签: java

最大限度地减少此代码并消除需要使用元素数组从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;
    }

1 个答案:

答案 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