Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

Lambda 식을 사용하여 ArrayList를 반복하는 Java 프로그램

<시간/>

이 기사에서는 람다 식을 사용하여 ArrayList를 반복하는 방법을 이해합니다. ArrayList 클래스는 java.util 패키지에서 찾을 수 있는 크기 조정 가능한 배열입니다. 자바의 내장 배열과 ArrayList의 차이점은 배열의 크기를 수정할 수 없다는 것입니다.

아래는 동일한 데모입니다 -

입력이 다음과 같다고 가정 -

Run the program

원하는 출력은 -

The list is defined as: Java Python Scala Mysql Redshift

알고리즘

Step 1 - START
Step 2 - Declare namely
Step 3 - Define the values.
Step 4 - Create an ArrayList, and iterate over it, and display it.
Step 5 - In the ArrayList, add elements using the ‘add’ method.
Step 6 - Display this on the console.
Step 7 - Use the ‘forEach’ loop to iterate over the elements, and display them.
Step 8 - Stop

예시 1

여기에서 모든 작업을 'main' 기능 아래에 묶습니다.

import java.util.ArrayList;
public class Demo {
   public static void print(ArrayList<String> input_list) {
      System.out.print("\nThe list is defined as:\n ");
      for(String language : input_list) {
         System.out.print(language + " ");
      }
   }
   public static void main(String[] args) {
      System.out.println("The required packages have been imported");
      ArrayList<String> input_list = new ArrayList<>();
      input_list.add("Java");
      input_list.add("Python");
      input_list.add("Scala");
      input_list.add("Mysql");
      input_list.add("Redshift");
      print(input_list);
   }
}

출력

The required packages have been imported

The list is defined as:
Java Python Scala Mysql Redshift

예시 2

여기에서 객체 지향 프로그래밍을 나타내는 함수로 작업을 캡슐화합니다.

import java.util.ArrayList;
public class Demo {
   public static void print(ArrayList<Integer> input_list) {
      System.out.print("\nThe list is defined as:\n ");
      for(Integer elements : input_list) {
         System.out.print(elements + " ");
      }
   }
   public static void main(String[] args) {
      System.out.println("The required packages have been imported");
      ArrayList<Integer> input_list = new ArrayList<>();
      input_list.add(500);
      input_list.add(600);
      input_list.add(700);
      input_list.add(800);
      input_list.add(950);
      print(input_list);
   }
}

출력

The required packages have been imported
The list is defined as:
500 600 700 800 950