Java之List使用方法
1 package basic; 2 3 import java.util.ArrayList; 4 import java.util.Arrays; 5 import java.util.Iterator; 6 import java.util.List; 7 import java.util.stream.Collectors; 8 9 //List使用方法 10 public class ListDemo { 11 12 public static void main(String[] args) { 13 // 实例化直接赋值 14 List<String> alpha = Arrays.asList("a", "b", "c", "d"); 15 dataPrintByFE(alpha); 16 17 // 实例化List 18 List<String> lists = new ArrayList<String>(); 19 20 // 添加元素 21 lists.add("a"); 22 lists.add("b"); 23 lists.add("c"); 24 lists.add("d"); 25 dataPrintByIt(lists); 26 lists.add(3, "e"); 27 dataPrintByIt(lists); 28 29 // 修改元素 30 lists.set(4, "f"); 31 dataPrintByIt(lists); 32 33 // 删除元素(index或object) 34 lists.remove(0); 35 lists.remove("b"); 36 dataPrintByForEach(lists); 37 38 // 查询 39 String item = lists.get(1); 40 int n = lists.indexOf("f"); 41 System.out.print("get:" + item + " indexOf:" + n); 42 43 // 遍歷(原始方法和新特性) 44 dataPrintByIt(lists); 45 dataPrintByForEach(lists); 46 47 // 清空 48 // lists.clear(); 49 50 // 直接输出 51 System.out.println("直接输出:" + lists); 52 53 // Java8处理输出 54 List<String> collect = lists.stream().map(String::toUpperCase).collect(Collectors.toList()); 55 System.out.println("Java8的stream输出:" + collect); // [A, B, C, D] 56 57 } 58 59 // 遍历list-原始方法 60 public static void dataPrintByIt(List<String> lists) { 61 Iterator<String> it = lists.iterator(); 62 while (it.hasNext()) { 63 System.out.print(it.next() + " "); 64 } 65 System.out.println(); 66 } 67 68 // 遍历list-forEach方法,Java8新特性 69 public static void dataPrintByForEach(List<String> lists) { 70 lists.forEach((x) -> System.out.print(x + " ")); 71 System.out.println(); 72 } 73 74 // 遍历list-forEach方法 75 public static void dataPrintByFE(List<String> lists) { 76 for (String item : lists) { 77 System.out.print(item + " "); 78 } 79 System.out.println(); 80 } 81 82 }
执行结果:
1 2 3 4 5 6 7 8 9 | a b c d a b c d a b c e d a b c e f c e f get:e indexOf:2c e f c e f 直接输出:[c, e, f] Java8的stream输出:[C, E, F] |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本