遍历数组、List、Map有几种方式

遍历数组、List、Map有几种方式

数组

String[] arr = {
     "a", "b", "c", "d", "e"};
//方法一:
for (int i = 0; i < arr.length; i++) {
     
	System.out.print(arr[i]);
}
//方法二:
for (String s : arr) {
     
    System.out.print(s);
}
//方法三:
Arrays.stream(arr).forEach(System.out::print);
//方法四:
System.out.println(Arrays.toString(arr));

List

		List<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("d");
        list.add("e");
        //方法一:
        for (int i = 0; i < list.size(); i++) {
     
            System.out.print(list.get(i));
        }
        //方法二:
        for (String s : list) {
     
            System.out.print(s);
        }
        //方法三:
        list.forEach(System.out::print);
        //方法四:
        Iterator<String> it = list.iterator();
        while (it.hasNext()){
     
            System.out.print(it.next());
        }

Map

		Map<String, String> map = new HashMap<>();
        map.put("a", "a");
        map.put("b", "b");
        map.put("c", "c");
        map.put("d", "d");
        map.put("e", "e");
        //方法一:
        for (Map.Entry<String, String> entry : map.entrySet()) {
     
            System.out.print(entry.getKey() + ":" + entry.getValue());
        }
        //方法二:
        for (String s : map.keySet()) {
     
            System.out.print(s + ":" + map.get(s));
        }
        //方法三:
        map.forEach((k, v) -> System.out.print(k + ":" + v));
        //方法四:
        for (String value : map.values()) {
     
            System.out.print(value);
        }
        //方法五:
        Iterator<String> it = map.keySet().iterator();
        while (it.hasNext()) {
     
            String next = it.next();
            System.out.print(next + ":" + map.get(next));
        }

你可能感兴趣的:(java)