0
点赞
收藏
分享

微信扫一扫

Java中数组和集合的for循环遍历

脱下愤怒的小裤衩 2022-04-04 阅读 49
java

传统的for循环遍历方式是

//对于数组而言
int[] arr=new int[10];
for(int i=0;i<arr.length;i++){
    System.out.print(i);
}

//对于集合要使用迭代器
List<String> list=new ArrayList<>();

for(Iterator<String> i=list.iterator();i.hasNext();){
    person=i.next();
    System.out.println(person);
}

现在有了for循环的增强形式,可以用很简单的办法迭代

//对于数组
for(int i:arr){
    int j=i;
}

//对于集合
for(Person p:list){
    String name=p.name;
}

这样特别方便。对于Map的迭代方式

//Map原本使用Entry的方式进行迭代
    HashMap<String, Integer> prices = new HashMap<>();
    
    prices.put("Shoes", 200);
    prices.put("Bag", 300);
    prices.put("Pant", 150);


    for(Entry<String,Integer> e:prices.entrySet()){
            System.out.println(e.getKey()+e.getValue());
    }


//现在可以直接用keySet
        for(String key:prices.keySet()){
            System.out.println(prices.get(key));
        }

还可以用Lambda表达式

prices.forEach((key,value) -> {
    System.out.println(key+" "+value);
});

话说本站的代码编辑器实在太难用了,格式都不带整一下的,这么多年了是怎么存下的。

举报

相关推荐

0 条评论