Stream为集合添加序号

Stream为集合添加序号

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class Test {

public static void main(String[] args) {
List<User> userList = new ArrayList<>();
User u1 = new User();
u1.setUserName("张三");
u1.setPassWord("zhangsan123");
userList.add(u1);

User u2 = new User();
u2.setUserName("李四");
u2.setPassWord("lisi123");
userList.add(u2);

User u3 = new User();
u3.setUserName("王五");
u3.setPassWord("wangwu123");
userList.add(u3);
//遍历添加序号
list.forEach(v -> v.setIndex(list.indexOf(v)+1));
}
}

@Data
public class User {

private Integer index;

private String userName;

private String passWord;
}
如果对您有帮助,可以打赏呦!