2

I have a List<List<Object>> type data. I need to add the same value in the List list. I tried the following but it doesn't work as its type is List<Boolean>.

List<List<Object>> data = ...;
data.stream().map(v -> v.add("test")).collect(Collectors.toList());

How can I get in same type List<List<Object>> ?

I have the following data:

"data": [
        [
            5,
            "Johnny",
            "Lollobrigida"                
        ],
        [
            6,
            "Bette",
            "Nicholson"               
        ],
        [
            7,
            "Grace",
            "Mostel"                
        ],
        [
            8,
            "Matthew",
            "Johansson"                
        ]
     ]

I want to change it to:

"data": [
        [
            5,
            "Johnny",
            "Lollobrigida",
            "test"
        ],
        [
            6,
            "Bette",
            "Nicholson",
            "test"               
        ],
        [
            7,
            "Grace",
            "Mostel" ,
            "test"               
        ],
        [
            8,
            "Matthew",
            "Johansson",
            "test"                
        ]
     ]
user1187329
  • 191
  • 1
  • 16

3 Answers3

5

@Boris the Spider is right : use forEach :

data.forEach(v -> v.add("test"));
user2189998
  • 718
  • 6
  • 10
2

List.add() returns a boolean, but you want your map() to return the List to which you added the new element.

You need:

List<List<Object>> out = 
    data.stream()
        .map(v -> {v.add("test"); return v;})
        .collect(Collectors.toList());

Note that if you don't want to mutate the original inner Lists, you can create a copy of them:

List<List<Object>> out = 
    data.stream()
        .map(v -> {
            List<Object> l = new ArrayList<>(v);
            l.add("test"); 
            return l;
        })
        .collect(Collectors.toList());
Eran
  • 387,369
  • 54
  • 702
  • 768
2

You need to return the list from map after adding the element. Below solution should work for you:

List<List<Object>> dataModified = data.stream().map(v -> {
    v.add("test");
    return v;
}).collect(Collectors.toList());
Amit Bera
  • 7,075
  • 1
  • 19
  • 42