1.StreamAPI 중간연산
- 필터링 : filter()/ 조건식 통과하는 요소만 남음, distinct() / 중복되는 요소 제거
- 변화 : map() / 특정 함수에 매핑, 새로운 요소 반환
- 제한 : limit(max) / 최대요소갯수 지정, 스트림제한 , skip(n) / 처음 n개 요소 제외, 스트림 재생성
- 정렬 : sorted() / 요소를 특정 정렬 순서에 따라 생성
package exercise.chapter_55;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class StreamIntermediateOpsTest {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Apple");
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Mango");
fruits.add("Grapes");
fruits.add("WaterMelon");
fruits.add("Pineapple");
fruits.add("Strawberry");
//filter : 특정 조건, ex. 길이가 6이상인 요소 선택
fruits.stream().filter(fruit -> fruit.length() >= 6).forEach(fruit -> System.out.println("필터 적용 fruit : " + fruit));
//distinct : 중복 요소 제거
List<String> fruitList = fruits.stream().distinct().collect(Collectors.toList());
System.out.println("중복 제거 전 : " + fruits);
System.out.println("중복 제거 후 : " + fruitList);
//map : 새로운 값으로 변환
List<String> fruitListMap = fruits.stream().map(fruit -> fruit.toUpperCase()).collect(Collectors.toList());
System.out.println("map 적용 후 : " + fruitListMap);
List<Integer> fruitListLength = fruits.stream().map(fruit -> fruit.length()).collect(Collectors.toList());
System.out.println("length map 적용 후 : " + fruitListLength);
//limit : 최대 갯수 지정
List<String> fruitList3 = fruits.stream().limit(3).collect(Collectors.toList());
System.out.println("limit 적용 후 : " + fruitList3);
//skip : 처음 n개 건너뛰고 선택
List<String> fruitList4 = fruits.stream().skip(3).collect(Collectors.toList());
System.out.println("skip 적용 후 : " + fruitList4);
//sorted : 정렬
List<String> fruitList5 = fruits.stream().sorted().collect(Collectors.toList());
System.out.println("sorted 적용 후 : " + fruitList5);
List<String> fruitList6 = fruits.stream().sorted((fruit1, fruit2) -> fruit1.length() - fruit2.length()).collect(Collectors.toList());
System.out.println("길이 순 정렬 : " + fruitList6);
}
}
- Java Comparator
@FunctionalInterface
public interface Comparator<T>{
int compare(T o1, To2);
}
// 0 : o1 == o2
// 양수 : o1 > o2
// 음수 : o1 < o2
1. Java I/O Stream
- Stream의 방향 : 일방통행
- 입력스트림 : 어떤 대상으로부터 자료를 읽어들일때 사용하는 스트림
- 출력스트림 : 파일에 저장할때 출력 스트림 사용
- 스트림의 단위 : 바이트스트림 / 문자(2바이트) 스트림
- Console 입출력 받기
- System.in / System.out / System.err : System 클래스에 있는 정적 변수 ( in, out, err )
import java.io.IOException;
public class ConsoleTest {
public static void main(String[] args) {
//System.in으로 입력받기
int i = 0;
System.out.print("입력하세요 : ");
try {
StringBuilder sb = new StringBuilder();
while ((i = System.in.read()) != '\n') {
sb.append((char) i);
}
System.out.println(sb);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
package exercise.chapter_56;
import java.util.Scanner;
public class ScannerTest {
//Scanner로 입력받기
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a name: ");
String name = scanner.nextLine();
System.out.print("Enter a job: ");
String job = scanner.nextLine();
System.out.print("Enter a age: ");
int age = scanner.nextInt();
System.out.printf("name : %s, job : %s, age : %d\n", name, job, age);
scanner.close();
}
}
2. 여러 종류 입출력
- file 입출력
- FileInputStream / FileOutputStream
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileInputStreamTest {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("src/exercise/chapter_56/test.txt")) {
int i;
while ((i = fis.read()) != -1) {
System.out.print((char) i);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileOutputStreamTest {
public static void main(String[] args) {
String content = "this is content of file\n";
try (FileOutputStream fos = new FileOutputStream("src/exercise/chapter_56/output.txt", true)) {
//FileOutputStream 의 두번째 인자를 true로 하면 덮어쓰기가 아닌 append로 내용 추가.
fos.write(content.getBytes());
System.out.println("output file created");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
- FileReader / FileWriter
public class FileReaderTest {
public static void main(String[] args) {
try (FileReader fr = new FileReader("src/exercise/chapter_56/test.txt");) {
int i;
while ((i = fr.read()) != -1) {
System.out.print((char) i);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class FileWriterTest {
public static void main(String[] args) {
String content = "한글 컨텐츠 입니다\n";
try (FileWriter fw = new FileWriter("src/exercise/chapter_56/output_korean.txt")) {
fw.write(content);
System.out.println("output file created");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 이미지 출력 ImageIO
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ImageIOTest {
public static void main(String[] args) {
String filePath = "src/exercise/chapter_56/oak.png";
try {
File file = new File(filePath);
BufferedImage image = ImageIO.read(file);
BufferedImage rotatedImage = rotateImage(image, 90);
String outputFilePath = "src/exercise/chapter_56/oak_output.png";
ImageIO.write(rotatedImage, "png", new File(outputFilePath));
System.out.println("이미지 파일 생성 완료");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static BufferedImage rotateImage(BufferedImage image, double angle) {
double radians = Math.toRadians(angle);
double sin = Math.abs(Math.sin(radians));
double cos = Math.abs(Math.cos(radians));
int width = image.getWidth();
int height = image.getHeight();
int newWidth = (int) Math.round(width * cos + height * sin);
int newHeight = (int) Math.round(height * sin + width * cos);
BufferedImage rotatedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_BGR);
Graphics2D graphics = rotatedImage.createGraphics();
graphics.translate((newWidth - width) / 2, (newHeight - height) / 2);
graphics.rotate(radians, width / 2, height / 2);
graphics.drawRenderedImage(image, null);
graphics.dispose();
return rotatedImage;
}
}
3. Java 보조 Stream
- 기존 기반 Stream 문자열 지원
- 기존 기반 Stream 성능 개선
- 기존 메소드를 사용하기 간편하게 개선
- InputStreamReader
import java.io.IOException;
import java.io.InputStreamReader;
public class InputStreamReaderTest {
public static void main(String[] args) {
//InputStreamReader로 개선, 바이트 단위가 아니고 문자열 단위로 읽어들임
int j = 0;
StringBuilder sb1 = new StringBuilder();
System.out.print("입력하세요 : ");
try (InputStreamReader isr = new InputStreamReader(System.in)) {
while ((j = isr.read()) != '\n') {
sb1.append((char) j);
}
System.out.println(sb1);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
- BufferedReader / BufferedWriter
import java.io.*;
public class BufferedStreamTest {
public static void main(String[] args) {
try (FileReader fr = new FileReader("src/exercise/chapter_56/test_long.txt");
FileWriter fw = new FileWriter("src/exercise/chapter_56/output_test_long.txt")) {
long start = System.currentTimeMillis();
int data;
while ((data = fr.read()) != -1) {
fw.write((char) data);
}
long end = System.currentTimeMillis();
System.out.println("Buffered 적용 전 : " + (end - start) + "ms");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
//BufferedReader/Writer로 개선
try (BufferedReader br = new BufferedReader(new FileReader("src/exercise/chapter_56/test_long.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("src/exercise/chapter_56/bufferd_output_long.txt"))
) {
long start = System.currentTimeMillis();
int data;
while ((data = br.read()) != -1) {
bw.write((char) data);
}
long end = System.currentTimeMillis();
System.out.println("Buffered 적용 전 : " + (end - start) + "ms");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
- PrintWriter로 개선
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class PrintWriterTest {
public static void main(String[] args) {
String fileName = "src/exercise/chapter_56/output.txt";
try (FileWriter fileWriter = new FileWriter(fileName)) {
fileWriter.write("FileWriter Example\n");
int num = 42;
String formattedNumber = String.format("정수형 format %d\n", num);
fileWriter.write(formattedNumber);
double value = 3.14;
String formattedValue = String.format("실수형 format %.2f", value);
fileWriter.write(formattedValue);
} catch (IOException e) {
throw new RuntimeException(e);
}
//PrintWriter로 개선, pritnln, printf 등 사용 가능
fileName = "src/exercise/chapter_56/output2.txt";
try (PrintWriter printWriter = new PrintWriter(fileName)) {
printWriter.println("FileWriter Example");
int num = 42;
printWriter.printf("정수형 format %d\n", num);
double value = 3.14;
printWriter.printf("실수형 format %.2f", value);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
#슈퍼코딩, #1:1관리형부트캠프, #백엔드, #backend, #백엔드공부, #개발공부, #백엔드개발자 #취준일기, #취준기록, #취뽀, #빡공, #HTML/CSS, #javascript, #react , #java, #spring