01 Stream
- 객체 저장소(ArrayList, List)에 저장된 객체들을 처리하는 다른 방식
총 인원수 구하기
StreamTest.java
package com.stream;
import java.util.ArrayList;
class Streaminfo {
String name;
int kor;
public Streaminfo() {}
public Streaminfo(String name, int kor) {
super();
this.name = name;
this.kor = kor;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getKor() {
return kor;
}
public void setKor(int kor) {
this.kor = kor;
}
}
public class StreamTest {
public static void main(String[] args) {
ArrayList<Streaminfo> alist = new ArrayList<Streaminfo>();
Streaminfo si = new Streaminfo();
alist.add(new Streaminfo("백두산", 90));
alist.add(new Streaminfo("한라산", 85));
alist.add(new Streaminfo("소백산", 100));
alist.add(new Streaminfo("광교산", 70));
alist.add(new Streaminfo("태백산", 99));
System.out.println("이름\t국어점수");
System.out.println("=================");
alist.forEach(k->System.out.println(k.getName() + "\t" + k.getKor()));
int cnt = (int)alist.stream().count();
System.out.println();
System.out.println("총 인원은 " + cnt + "명 입니다.");
}
}
① alist.stream().count(); // long형이므로 int로 형변환
[결과화면]
총합 구하기
StreamTest.java
package com.stream;
import java.util.ArrayList;
public class StreamTest {
// 생략
public static void main(String[] args) {
ArrayList<Streaminfo> alist = new ArrayList<Streaminfo>();
Streaminfo si = new Streaminfo();
alist.add(new Streaminfo("백두산", 90));
alist.add(new Streaminfo("한라산", 85));
alist.add(new Streaminfo("소백산", 100));
alist.add(new Streaminfo("광교산", 70));
alist.add(new Streaminfo("태백산", 99));
System.out.println("이름\t국어점수");
System.out.println("=================");
alist.forEach(k->System.out.println(k.getName() + "\t" + k.getKor()));
int sum = alist.stream().mapToInt(Streaminfo::getKor).sum();
System.out.println();
System.out.println("국어 점수의 총 합은 " + sum + "점 입니다.");
}
}
① alist.stream().mapToInt(클래스명::get).sum();
[결과화면]
평균 구하기
StreamTest.java
package com.stream
import java.util.ArrayList;
public class StreamTest {
// 생략
public static void main(String[] args) {
ArrayList<Streaminfo> alist = new ArrayList<Streaminfo>();
Streaminfo si = new Streaminfo();
alist.add(new Streaminfo("백두산", 90));
alist.add(new Streaminfo("한라산", 85));
alist.add(new Streaminfo("소백산", 100));
alist.add(new Streaminfo("광교산", 70));
alist.add(new Streaminfo("태백산", 99));
System.out.println("이름\t국어점수");
System.out.println("=================");
alist.forEach(k->System.out.println(k.getName() + "\t" + k.getKor()));
double avg = alist.stream().mapToInt(Streaminfo::getKor).average().getAsDouble();
System.out.println();
System.out.println("국어 점수의 총 평균은 " + avg + "점 입니다.");
}
}
① alist.stream().mapToInt(클래스명::get).average().getAsDouble();
[결과화면]
조건문 추가하기
StreamTest.java
package com.stream;
import java.util.ArrayList;
public class StreamTest {
// 생략
public static void main(String[] args) {
ArrayList<Streaminfo> alist = new ArrayList<Streaminfo>();
Streaminfo si = new Streaminfo();
alist.add(new Streaminfo("백두산", 90));
alist.add(new Streaminfo("한라산", 85));
alist.add(new Streaminfo("소백산", 100));
alist.add(new Streaminfo("광교산", 70));
alist.add(new Streaminfo("태백산", 99));
System.out.println("이름\t국어점수");
System.out.println("=================");
alist.forEach(k->System.out.println(k.getName() + "\t" + k.getKor()));
int cnt = (int)(alist.stream().filter(k->k.getKor()>=90).count());
System.out.println();
System.out.println("90점 이상인 인원 수는 " + cnt + "명 입니다.");
}
}
① alist.sream().filter(조건).count(); // (k: 임의변수)
[결과화면]
조건문 추가하기 (목록 출력)
StreamTest.java
package com.stream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class StreamTest {
// 생략
public static void main(String[] args) {
ArrayList<Streaminfo> alist = new ArrayList<Streaminfo>();
Streaminfo si = new Streaminfo();
alist.add(new Streaminfo("백두산", 90));
alist.add(new Streaminfo("한라산", 85));
alist.add(new Streaminfo("소백산", 100));
alist.add(new Streaminfo("광교산", 70));
alist.add(new Streaminfo("태백산", 99));
System.out.println("이름\t국어점수");
System.out.println("=================");
alist.forEach(k->System.out.println(k.getName() + "\t" + k.getKor()));
List<Streaminfo> k_list = alist.stream().filter(k->k.getKor()>=90).collect(Collectors.toList());
System.out.println();
System.out.println("90점 이상인 인원 출력");
System.out.println("=================");
k_list.forEach(k->System.out.println(k.getName() + "\t" + k.getKor()));
}
}
① filter: 조건
② collect: List 목록
[결과화면]
02 Stream으로 정렬하기
이름별 오름차순
SortTest.java
package com.stream;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class SortTest {
String name;
int kor;
int eng;
public SortTest() {}
public SortTest(String name, int kor, int eng) {
super();
this.name = name;
this.kor = kor;
this.eng = eng;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getKor() {
return kor;
}
public void setKor(int kor) {
this.kor = kor;
}
public int getEng() {
return eng;
}
public void setEng(int eng) {
this.eng = eng;
}
public static void main(String[] args) {
ArrayList<SortTest> alist = new ArrayList<SortTest>();
alist.add(new SortTest("백두산", 56, 75));
alist.add(new SortTest("한라산", 90, 98));
alist.add(new SortTest("소백산", 66, 56));
alist.add(new SortTest("태백산", 74, 48));
alist.add(new SortTest("광교산", 89, 100));
alist.add(new SortTest("설악산", 100, 81));
alist.add(new SortTest("도봉산", 99, 99));
System.out.println("이름\t국어점수\t영어점수");
System.out.println("========================");
List<SortTest> name_asc = alist.stream().sorted(Comparator.comparing(SortTest::getName)).collect(Collectors.toList());
name_asc.forEach(k->System.out.println(k.getName() + "\t" + k.getKor() + "\t" + k.getEng()));
}
}
① alist.stream().sorted(Comparator.comparing(클래스명::get)).collect(Collectors.toList());
② getName 오름차순으로 정렬
[결과화면]
이름별 내림차순
SortTest.java
package com.stream;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class SortTest {
// 생략
public static void main(String[] args) {
ArrayList<SortTest> alist = new ArrayList<SortTest>();
alist.add(new SortTest("백두산", 56, 75));
alist.add(new SortTest("한라산", 90, 98));
alist.add(new SortTest("소백산", 66, 56));
alist.add(new SortTest("태백산", 74, 48));
alist.add(new SortTest("광교산", 89, 100));
alist.add(new SortTest("설악산", 100, 81));
alist.add(new SortTest("도봉산", 99, 99));
System.out.println("이름\t국어점수\t영어점수");
System.out.println("========================");
List<SortTest> name_asc = alist.stream().sorted(Comparator.comparing(SortTest::getName).reversed()).collect(Collectors.toList());
name_asc.forEach(k->System.out.println(k.getName() + "\t" + k.getKor() + "\t" + k.getEng()));
}
}
① alist.stream().sorted(Comparator.comparing(클래스명::get).reversed()).collect(Collectors.toList())
[결과화면]
이름별 오름차순 + 국어점수별 오름차순
SortTest.java
package com.stream;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class SortTest {
// 생략
public static void main(String[] args) {
ArrayList<SortTest> alist = new ArrayList<SortTest>();
alist.add(new SortTest("백두산", 56, 75));
alist.add(new SortTest("한라산", 90, 98));
alist.add(new SortTest("백두산", 66, 56));
alist.add(new SortTest("백두산", 74, 48));
alist.add(new SortTest("한라산", 89, 100));
alist.add(new SortTest("한라산", 100, 81));
alist.add(new SortTest("백두산", 99, 99));
System.out.println("이름\t국어점수\t영어점수");
System.out.println("========================");
List<SortTest> name_asc = alist.stream().sorted(Comparator.comparing(SortTest::getName).thenComparing(SortTest::getKor)).collect(Collectors.toList());
name_asc.forEach(k->System.out.println(k.getName() + "\t" + k.getKor() + "\t" + k.getEng()));
}
}
① alist.stream().sorted(Comparator.comparing(클래스명::get).thenComparing(클래스명::get)).collect(Collectors.toList())
[결과화면]
이름별 내림차순 + 국어점수별 내림차순
SortTest.java
package com.stream;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class SortTest {
// 생략
public static void main(String[] args) {
ArrayList<SortTest> alist = new ArrayList<SortTest>();
alist.add(new SortTest("백두산", 56, 75));
alist.add(new SortTest("한라산", 90, 98));
alist.add(new SortTest("백두산", 66, 56));
alist.add(new SortTest("백두산", 74, 48));
alist.add(new SortTest("한라산", 89, 100));
alist.add(new SortTest("한라산", 100, 81));
alist.add(new SortTest("백두산", 99, 99));
System.out.println("이름\t국어점수\t영어점수");
System.out.println("========================");
Comparator<SortTest> kor_des = Comparator.comparing(SortTest::getKor).reversed();
List<SortTest> name_asc = alist.stream().sorted(Comparator.comparing(SortTest::getName).reversed().thenComparing(kor_des)).collect(Collectors.toList());
name_asc.forEach(k->System.out.println(k.getName() + "\t" + k.getKor() + "\t" + k.getEng()));
}
}
① 국어 점수별 내림차순 객체 생성: Comparator<클래스명> 변수명1 = Comparator.comparing(클래스명::get).reversed();
② 이름별 내림차순 정렬에 ① 추가: alist.stream().sorted(Comparator.comparing(클래스명::get).reversed().thenComparing(변수명1))
[결과화면]
이름별 내림차순 + 국어점수별 오름차순
SortTest.java
package com.stream;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class SortTest {
// 생략
public static void main(String[] args) {
ArrayList<SortTest> alist = new ArrayList<SortTest>();
alist.add(new SortTest("백두산", 56, 75));
alist.add(new SortTest("한라산", 90, 98));
alist.add(new SortTest("백두산", 66, 56));
alist.add(new SortTest("백두산", 74, 48));
alist.add(new SortTest("한라산", 89, 100));
alist.add(new SortTest("한라산", 100, 81));
alist.add(new SortTest("백두산", 99, 99));
System.out.println("이름\t국어점수\t영어점수");
System.out.println("========================");
List<SortTest> name_asc = alist.stream().sorted(Comparator.comparing(SortTest::getName).reversed().thenComparing(SortTest::getKor)).collect(Collectors.toList());
name_asc.forEach(k->System.out.println(k.getName() + "\t" + k.getKor() + "\t" + k.getEng()));
}
}
① alist.stream().sorted(Comparator.comparing(클래스명::get).reversed().thenComparing(클래스명::get))
[결과화면]
이름별 오름차순 + 국어점수별 내림차순
SortTest.java
package com.stream;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class SortTest {
// 생략
public static void main(String[] args) {
ArrayList<SortTest> alist = new ArrayList<SortTest>();
alist.add(new SortTest("백두산", 56, 75));
alist.add(new SortTest("한라산", 90, 98));
alist.add(new SortTest("백두산", 66, 56));
alist.add(new SortTest("백두산", 74, 48));
alist.add(new SortTest("한라산", 89, 100));
alist.add(new SortTest("한라산", 100, 81));
alist.add(new SortTest("백두산", 99, 99));
System.out.println("이름\t국어점수\t영어점수");
System.out.println("========================");
Comparator<SortTest> kor_des = Comparator.comparing(SortTest::getKor).reversed();
List<SortTest> name_asc = alist.stream().sorted(Comparator.comparing(SortTest::getName).thenComparing(kor_des)).collect(Collectors.toList());
name_asc.forEach(k->System.out.println(k.getName() + "\t" + k.getKor() + "\t" + k.getEng()));
}
}
① 국어 점수별 내림차순 객체 생성: Comparator<클래스명> 변수명1 = Comparator.comparing(클래스명::get).reversed();
② 이름별 오름차순 정렬에 ① 추가: alist.stream().sorted(Comparator.comparing(클래스명::get).thenComparing(변수명1))
[결과화면]
03 Map을 이용해서 Stream 사용
성별로 그룹지어 국어 총점 구하기
MapTest.java
package com.stream;
import java.util.ArrayList;
import java.util.Map;
import java.util.stream.Collectors;
public class MapTest {
enum Gender{남자, 여자}
String name;
int kor, eng;
Gender gender;
public MapTest() { }
public MapTest(String name, int kor, int eng, MapTest.Gender gender) {
super();
this.name = name;
this.kor = kor;
this.eng = eng;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getKor() {
return kor;
}
public void setKor(int kor) {
this.kor = kor;
}
public int getEng() {
return eng;
}
public void setEng(int eng) {
this.eng = eng;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public static void main(String[] args) {
ArrayList<MapTest> alist = new ArrayList<MapTest>();
alist.add(new MapTest("백두산", 80, 65, MapTest.Gender.남자));
alist.add(new MapTest("한라산", 77, 64, MapTest.Gender.여자));
alist.add(new MapTest("태백산", 66, 78, MapTest.Gender.남자));
alist.add(new MapTest("소백산", 78, 71, MapTest.Gender.여자));
alist.add(new MapTest("백두산", 90, 83, MapTest.Gender.여자));
alist.add(new MapTest("소백산", 99, 90, MapTest.Gender.여자));
alist.add(new MapTest("한라산", 100, 89, MapTest.Gender.남자));
System.out.println("이름\t국어점수\t영어점수\t성별");
System.out.println("=============================");
alist.forEach(k->System.out.println(k.getName() + "\t" + k.getKor() + "\t" + k.getEng() + "\t" + k.getGender()));
System.out.println();
System.out.println("=============================");
Map<MapTest.Gender, Integer> m_sum = alist.stream().collect(Collectors.groupingBy(MapTest::getGender, Collectors.summingInt(MapTest::getKor)));
System.out.println("남자 국어 총점 = " + m_sum.get(MapTest.Gender.남자));
int w_kor = alist.stream().filter(k->k.getGender()==MapTest.Gender.여자).mapToInt(MapTest::getKor).sum();
System.out.println("여자 국어 총점 = " + w_kor);
}
}
① enum을 사용해 성별은 남자와 여자만 입력받기
② Map 이용(남자 그룹): Map<MapTest.Gender, Integer> m_sum = alist.stream().collect(Collectors.groupingBy(MapTest::getGender, Collectors.summingInt(MapTest::getKor)));
③ filter 이용(여자 그룹): alist.stream().filter(k->k.getGender()==MapTest.Gender.여자).mapToInt(MapTest::getKor).sum();
[결과화면]
Map 구조로 출력하기
MapTest.java
package com.stream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class MapTest {
enum Gender{남자, 여자}
String name;
int kor, eng;
Gender gender;
public MapTest() { }
public MapTest(String name, int kor, int eng, MapTest.Gender gender) {
super();
this.name = name;
this.kor = kor;
this.eng = eng;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getKor() {
return kor;
}
public void setKor(int kor) {
this.kor = kor;
}
public int getEng() {
return eng;
}
public void setEng(int eng) {
this.eng = eng;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public static void main(String[] args) {
ArrayList<MapTest> alist = new ArrayList<MapTest>();
alist.add(new MapTest("백두산", 80, 65, MapTest.Gender.남자));
alist.add(new MapTest("한라산", 77, 64, MapTest.Gender.여자));
alist.add(new MapTest("태백산", 66, 78, MapTest.Gender.남자));
alist.add(new MapTest("소백산", 78, 71, MapTest.Gender.여자));
alist.add(new MapTest("백두산", 90, 83, MapTest.Gender.여자));
alist.add(new MapTest("소백산", 99, 90, MapTest.Gender.여자));
alist.add(new MapTest("한라산", 100, 89, MapTest.Gender.남자));
System.out.println("이름\t성별\t국어점수\t영어점수");
System.out.println("=============================");
Map<MapTest.Gender, List<MapTest>> m_kor = alist.stream().collect(Collectors.groupingBy(MapTest::getGender));
m_kor.get(MapTest.Gender.남자).forEach(k->System.out.println(k.getName() + "\t" + k.getGender() + "\t" + k.getKor() + "\t" + k.getEng()));
}
}
① 성별로 그룹지어 Map 구조에 저장
② 성별이 남자일 때 이름, 성별, 국어, 영어 점수 출력
[결과화면]
'STUDY > Java' 카테고리의 다른 글
<자바의 신> 1장 프로그래밍이란 무엇인가? (0) | 2023.12.09 |
---|---|
아파치 톰캣(Apache-Tomcat) 설치 (0) | 2021.11.05 |
[JAVA] 람다식, Enum (0) | 2021.11.05 |
[JAVA] Collection (List, Set, Map) (0) | 2021.11.05 |
[JAVA] Generic 제네릭 (0) | 2021.11.05 |