Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java stream how to add value in nested List of List

Tags:

java

java-8

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"                
        ]
     ]
like image 345
user1187329 Avatar asked Jan 01 '26 07:01

user1187329


2 Answers

@Boris the Spider is right : use forEach :

data.forEach(v -> v.add("test"));
like image 67
user2189998 Avatar answered Jan 06 '26 00:01

user2189998


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());
like image 45
Eran Avatar answered Jan 05 '26 23:01

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!