2

I was wondering if one can get a List from an object, add an item to it, and set the List to the object in one line.

I would normally do it this way:

List<String> tempList = someObject.getList();
tempList.add("some string value");
someObject.setList(tempList);

What I tried doing was this:

someObject.setList(someObject.getList().add("some string value"));

But then I realized that the method add() would return a boolean while the method setList() takes a List<String>

Any ideas?

yogur
  • 810
  • 10
  • 19

3 Answers3

5

As far as I know there is no nice way to do this in one line.

If you need to do this a lot, you could modify the class of someObject to have an addItem method to do this directly.

Alternatively, if you cannot modify the class, you could write a method for adding to a list and returning the list:

static <E> List<E> add(List<E> list, E extra) {
    list.add(extra);
    return list; 
}
Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
  • 1
    +1 for a simple solution. I knew I could do this, but wanted to know if I could do it directly without creating new methods. – yogur Jan 03 '17 at 14:56
4

Assuming you aren't returning a copy in getList it should be the same reference, so you can say

someObject.getList().add("some string value");

And you should not need to setList back, because there is only one List.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • May you offer more explanation on how it works. I was not aware that we could manipulate objects by reference in Java. – yogur Jan 03 '17 at 14:55
  • 1
    [Is Java “pass-by-reference” or “pass-by-value”?](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) Java is always pass by value, but the value of objects (reference types) **is-a** reference. – Elliott Frisch Jan 03 '17 at 15:48
2

Just because you can do something in one statement, doesn't mean you should!

But it's certainly possible if you don't mind abusing the streams a little bit:

    Stream.of(someObject.getList())
            .map(list -> new Pair<>(list.add(new Object()), list))
            .forEach(pair -> someObject.setList(pair.getValue()));

Of course the real answer is, if you want to do things like this in one line you should simply write a method with as many lines as needed for clarity, then call it (in one line).

Patrick Parker
  • 4,863
  • 4
  • 19
  • 51