써먹는 웹개발

[Java] ArrayList를 받아오는 3가지 방법 본문

웹개발/Java & Jsp

[Java] ArrayList를 받아오는 3가지 방법

kmhan 2018. 7. 12. 16:14


728x90
반응형

ArrayList를 받아오는 3가지 방법

1. for문

ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(1,2,3));
for( int i = 0; i < list.size(); i++) {
  int num = list.get(i);
  System.out.println("값 : "+num);
}

 

2. Iterator

ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(1,2,3));
Iterator<Integer> iter = list.iterator();
while(iter.hasNext()) {
  int num = iter.next();
  System.out.println("값 : " + num);
}

 

3. Stream : 컬렉션의 저장 요소를 하나씩 참조해서 람다식으로 처리할 수 있도록 해주는 반복자 

 ※ 자바 8부터 추가

// ArrayList
ArrayList<Integer> list =
new ArrayList<Integer>(Arrays.asList(1,2,3));
Stream<Integer> stream = list.stream();
stream.forEach(num -> System.out.println(
"값 : "+num));
// String 배열
String[] strArray = { "테", "스", "트"};
Stream<String> strStream = Arrays.stream(strArray);
strStream.forEach(a -> System.out.print(a +
","));
// int 배열
int[] intArray = { 1, 2, 3, 4, 5 };
IntStream intStream = Arrays.stream(intArray);
intStream.forEach(a -> System.out.print(a +
","));

 

 - 클래스에서의 stream 활용

class Student {
  private String name;
  private int score;

  public Student(String name, int score) {
    this.name = name;
    this.score = score;
  }
 
  public
String getName() { return name; }
  public int getScore() { return score; }
}

public class FromCollectionExample {
  public static void main(String[] args) {
    List<Student> studentList = Arrays.asList(
      new Student("홍길동", 10),
      new Student("이순신", 20),
      new Student("임꺽정", 30)
    );

    Stream<Student> stream = studentList.stream();
    stream.forEach(s -> System.out.println(
"이름 : "+ s.getName()));
  }
}

출처 : coding-factory.tistory.com/574?category=758267


2018.07.12

 그동안 배열이나 ArrayList등을 사용할 때 데이터 전체를 받기 위해서 반복문과 index값을 이용해 데이터에 접근해 왔다. for( int i = 0 ; i < arr.length ; i++){ arr[i] } 이런 식으로 말이다. 이걸 대체할 수 있는 것이 바로 Iterator이다. Iterator는 컬렉션 클래스가 가진 데이터를 순차적으로 참조할 수 있는 기능을 가진 인스턴스라고 볼 수 있다. 자바의 Collection은 공통적으로 iterator()가 정의되어 있기 때문에 이걸 사용하면 어떤 클래스이건 동일한 방식으로 데이터를 순차적으로 참조 할 수 있다는 특징이 있다. 즉, 컬렉션 클래스 교체에 따른 영향이 없다.

 

 

[표] Iterator<E>에 정의된 메소드 4가지

 

반환 자료형
메소드
설명
default void
forEachRemaining(Consumer<? superE> action)
모든 원소가 처리된거나 예외가 발생할 때 까지 주어진 action을 수행한다.
boolean
hasNext()
다음 원소가 존재하면 true를 반환
E
next()
다음 원소를 반환
default void
remove()
마지막에 반환했던 위치의 요소를 삭제

 

 

[출처] 자바공부30. Collections 02 - 반복자(Iterator)|작성자 아무거시

 

-------------------------------------------------------------------------------------------------------

 

Q) Iterator에서 읽어 올 요소가 있는지 여부를 구하는 메소드는?

A) hasNext(); // 있으면 true, 없으면 false를 반환

 

ex) Iterator fileNames = multiPartRequest.getFileNames();

     fileNames.hasNext();

 

 

 

 

 

728x90
반응형


Comments