首页 > 学院 > 开发设计 > 正文

Java 集合List Set Map 循环的遍历 EnumMap集合的操作

2019-11-14 09:12:28
字体:
来源:转载
供稿:网友

1:List集合遍历的方式(ArrayList为例) 1.1 实体类 public class User { PRivate String username; private String address; private int age;

public User() { super();}public User(String username, String address, int age) { super(); this.username = username; this.address = address; this.age = age;}public String getUsername() { return username;}public void setUsername(String username) { this.username = username;}public String getAddress() { return address;}public void setAddress(String address) { this.address = address;}public int getAge() { return age;}public void setAge(int age) { this.age = age;}@Overridepublic String toString() { return "User [username=" + username + ", address=" + address + ", age=" + age + "]";}

} 1.2向集合中添加User对象 List list=new ArrayList<>();

List<User> list1=new ArrayList<>(); User user1=new User("刘备","今河北省保定市涿州市",1800); User user2=new User("张飞","河北",1800); User user3=new User("关羽","山西解梁",1800); User user4=new User("赵云","河北常山",1800); User user5=new User("诸葛亮","河南南阳",1800); list.add(user1); list.add(user2); list.add(user3); list.add(user4); list.add(user5); System.out.println("list集合foreach循环"); for (User user : list) { if(user.getUsername().equals("刘备")){ user.setAddress("搬迁到四川成都成为蜀国的君王"); } System.out.println("姓名:"+user.getUsername()+",户籍:"+user.getAddress()+ ",年龄:"+user.getAge()); } System.out.println("list集合for循环"); for(int i=0;i<list.size();i++){ System.out.println("姓名:"+list.get(i).getUsername()+",户籍:"+list.get(i).getAddress()+ ",年龄:"+list.get(i).getAge()); } System.out.println("list集合Iterator"); if(list1.isEmpty()){ System.out.println("list1集合为空"); } Iterator<User> it=list1.iterator(); while(it.hasNext()){ System.out.println(it.next()); } System.out.println("list集合Lamda循环"); list.forEach(l->System.out.println(l));

2:Set集合的遍历(HashSet为例,不能使用for循环遍历) Set set = new HashSet<>(); User user1 = new User(“刘备”, “今河北省保定市涿州市”, 1800); User user2 = new User(“张飞”, “河北”, 1800); User user3 = new User(“关羽”, “山西解梁”, 1800); User user4 = new User(“赵云”, “河北常山”, 1800); User user5 = new User(“诸葛亮”, “河南南阳”, 1800); set.add(user1); set.add(user2); set.add(user3); set.add(user4); set.add(user5); System.out.println(“set集合foreach循环”); for (User user : set) { if (user.getUsername().equals(“刘备”)) { user.setAddress(“搬迁到四川成都成为蜀国的君王”); } System.out.println(“姓名:” + user.getUsername() + “,户籍:” + user.getAddress() + “,年龄:” + user.getAge()); } System.out.println(“set集合Iterator”); if (set.isEmpty()) { System.out.println(“set1集合为空”); } Iterator it = set.iterator(); while (it.hasNext()) { System.out.println(it.next()); } System.out.println(“set集合Lamda循环”); set.forEach(l -> System.out.println(l)); 3:Map集合的遍历(HashMap为例) Map


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表