1

What's the best way to minimize this code and also remove the need for a element array to assign the variable with the value from inside the 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;
    }
3
  • Just use normal for/each loops: for (User user : usersModel) Commented Nov 14, 2018 at 23:59
  • User widgetModel = (((AuthManagerRow) getWidget(i)).getModel(); - save a few lines Commented Nov 15, 2018 at 0:01
  • IntStream.of(int) returns a stream with a single element. Did you actually mean to use IntStream.range(0, getWidgetCount())? Commented Nov 15, 2018 at 0:18

1 Answer 1

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());

Assuming User.getObjectId() returns Integer.

Sign up to request clarification or add additional context in comments.

1 Comment

because only the first User for the given ObjectId should be returned

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.