Stream为集合添加序号 发表于 2021-08-06 | 分类于 小技巧 Stream为集合添加序号1234567891011121314151617181920212223242526272829303132public 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)); }} @Datapublic class User { private Integer index; private String userName; private String passWord;} 如果对您有帮助,可以打赏呦! 打赏 微信支付 支付宝