본문 바로가기
Web/JAVA

Collection, lamda

by 당진개발자 2024. 1. 23.

※ List, Set, Map과 같은 인터페이스는 java.util의 패키지이다.

※ List와 Set은 Collection을 상속 받는다.

※ CRUD 메서드를 사용

 

1. List

  1) 특징

    - 입력 순서가 있는 데이터 집합

    - 데이터의 중복을 허락

    - ex) ArrayList, LinkedList

List<자료형> 이름 = new ArrayList<>() or new LinkedList<>();

 

  2) 주요 메서드

 


 

2. 배열과 ArrayList

※ 배열을 사용하는 ArrayList도 태생적으로 배열의 장-단점을 그래도 가져감

  1) 배열의 장점

    - 간단하며 사용이 쉬움

    - 접근 속도가 빠름

  2) 배열의 단점

    - 크기 변경이 불가능하여 추가 데이터를 위해 새로운 배열을 만들고 복사해야함

    - 비 순차적 데이터의 추가, 삭제에 많은 시간이 걸림

 


 

3. LinkedList

    - 각 요소를 Node로 정의하고 Node는 다음 요소의 참조 값과 데이터로 구성됨 (연속 X)

    - 데이터 삭제 및 추가에 시간이 적게 소요

 


 

4. ArrayList와 LinkedList

    - 정적인 데이터 활용, 단순한 데이터 조회용 : ArrayList

    - 동적인 데이터 추가, 삭제가 많은 작업 : LinkedList

 


 

5. Set

  1) Set의 특징

    - 입력 순서를 관리하지 않고 주머니에 데이터를 넣는 형태

    - 인덱스가 존재하지 않기 때문에 중복이 허용되지 않는다.

    - CRD의 메소드만 존재한다. (인덱스가 없기 때문)

    - 동일한 데이터의 기준은 객체의 equals()가 true를 리턴하고 hashCode() 값이 같을 것.

@Override
public boolean equals(Object obj) {
    if (obj != null && obj instanceof SmartPhone phone) {
        return this.number.equals(phone.number);
    }
    return false;
}

@Override
public int hashCode() {
    return this.number.hashCode();
}

 

    - ex) HashSet

Set<Object> hset = new HashSet<Object>();

 

  2) 주요 메서드

 


 

6. Map

  1) Map의 특징

    - Collection을 상속받지 않는다.

    - Key(Object 형태, 중복 X)와 Value (Object 형태, 중복 O) 를 하나의 Entry로 묶어서 데이터 관리

    - ex) HashMap, SortedMap

Map<String, String> hMap = new HashMap<>();

 

  2) 주요 메서드

 


 

7. 정렬

  1) 정렬의 특징

    - 요소를 특정 기준에 따라 내림차순 또른 오름차순으로 배치하는 것

    - 순서를 가지는 Collection들만 정렬 가능

    - sort(List<T> list)를 사용하여 정렬

    - 객체를 정렬 Comparable을 상속받아야 함)

public class SmartPhone implements Comparable<SmartPhone> {
	@Override
	public int compareTo(SmartPhone o) {
		return number.compareTo(o.number); // int는 Comparable를 상속하기 때문에
	}
}

 

    - Comparator를 생성한 후 정렬 기준 생성 (ex. 내림차순 정렬)

// 내림차순 정렬
Collections.sort(list, Collections.reverseOrder());
/*
 1. 파일 생성(student.txt)
 이름:자바점수:SQL점수:JDBC점수
 */

package com.ssafy.day7.offline;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

public class SortTest {
	static class Student implements Comparable<Student>{
		String name;
		int javaScore;
		int sqlScore;
		int jdbcScore;

		public Student() {
		}

		public Student(String name, int javaScore, int sqlScore, int jdbcScore) {
			super();
			this.name = name;
			this.javaScore = javaScore;
			this.sqlScore = sqlScore;
			this.jdbcScore = jdbcScore;
		}

		@Override
		public String toString() {
			return "Student [name=" + name + ", javaScore=" + javaScore + ", sqlScore=" + sqlScore + ", jdbcScore="
					+ jdbcScore + "]";
		}

		@Override
		public int compareTo(Student o) {
			return this.name.compareTo(o.name) * -1;
		}
	}

	private final String path = "src/com/ssafy/day7/offline/student.txt";
	private List<Student> studentList = new ArrayList<>();
	
	private void service() throws Exception {
		fileLoding();
//		System.out.println(studentList);
		System.out.println("학생 정보를 이름순으로 출력");
		printOrderByName();
		System.out.println("학생 정보를 자바 점수 순으로 출력");
		printOrderByJavaScore();
		System.out.println("학생 정보를 총 점수가 높은순으로 출력");
		printOrderBytotalScore();
	}
	
	static class JavaTotalScoreComparator implements Comparator<Student> {
		@Override
		public int compare(Student o1, Student o2) {
			return getTotalScore(o1) - getTotalScore(o2);
		}
	}
	
	static int getTotalScore(Student student) {
		int totalScore = student.javaScore + student.jdbcScore + student.sqlScore;
		return totalScore;
	}
	
	private void printOrderBytotalScore() {
		
		Collections.sort(studentList, new JavaTotalScoreComparator());
		
		// 익명 클래스
		Collections.sort(studentList, new Comparator<Student>() {
			public int compare(Student o1, Student o2) {
				return getTotalScore(o1) - getTotalScore(o2);
			}
		});
		
		// 람다 식
		Collections.sort(studentList, (o1, o2) -> {
				return getTotalScore(o1) - getTotalScore(o2);
		});
		
		for (Student s : studentList) {
			System.out.println(s);
		}
	}

	static class JavaScoreComparator implements Comparator<Student> {
		@Override
		public int compare(Student o1, Student o2) {
			return o1.javaScore - o2.javaScore;
		}
	}

	private void printOrderByJavaScore() {
		Collections.sort(studentList, new JavaScoreComparator());
		for (Student s : studentList) {
			System.out.println(s);
		}
	}

	private void printOrderByName() {
		Collections.sort(studentList);
		for (Student s : studentList) {
			System.out.println(s);
		}
	}

	private void fileLoding() throws Exception {
		File f = new File(path);
		Scanner sc = new Scanner(f);
		while (sc.hasNextLine()) {
			String[] arr = sc.nextLine().split(":");
			studentList.add(new Student(arr[0], 
							Integer.parseInt(arr[1]),
							Integer.parseInt(arr[2]),
							Integer.parseInt(arr[3])
			));
		}
		sc.close();
	}

	public static void main(String[] args) {
		try {
			new SortTest().service();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 


8. lamda

  1) lamda식이란?

    - 함수적 프로그래밍의 형태로 재상용 가능한 코드 블록

    - 익명함수를 지칭하는 용어

A a = (매개값) -> { 구현코드 };

 

  2) lamda함수 조건

    - 이름을 가질 필요가 없다.

    - 추상메서드가 하나만 존재한다.

  3) 람다식 예

@FunctionalInterface // 추상메서드가 하나있어!
interface Server {
	void start();
}

public class LamdaTest01 {
	public static void main(String[] args) {
    
    	// 내부 클래스
		class WebServer implements Server {
			public void start() {
				System.out.println("WebServer start~");
			}
		}
		Server server = new WebServer();
		startServer(server);
        
        // 변환
        startServer(new Server() { // 부모의 클래스나 인터페이스
			public void start() {
				System.out.println("익명 : WebServer start~");
			}
		});
        
        // 람다식 표현
        startServer(() -> {
			System.out.println("익명 : WebServer start~");
		});
        
    }
    
    private static void startServer(Server server) {
		server.start();
	}
}

 


 

9. 표준 API

  1) 기본 제공 API 종류

    - Consumer : void accept(T)

    - Supplier : T get()

package com.ssafy.day7.offline;

import java.util.function.IntSupplier;
import java.util.function.Supplier;

public class LamdaTest03_Supplier {
	public static void main(String[] args) {
		test01();
	}

	private static void test01() {
		
		// 익명 클래스
		Supplier<String> supplier = new Supplier<String>() {
			@Override
			public String get() {
				return "hello";
			}
		};
		System.out.println(supplier.get());
		
		// 람다
		Supplier<String> supplier1 = () -> {return "hello";};
		System.out.println(supplier1.get());
		
		// 람다
		IntSupplier is = () -> 100;
		System.out.println(is.getAsInt());
	}
}

 

    - Funtion : T apply(R)

public class LamdaTest04_Function {
	
	static class Student {
		String name;
		int java;
		int algo;
		public Student() {
		}
		public Student(String name, int java, int algo) {
			super();
			this.name = name;
			this.java = java;
			this.algo = algo;
		}
	}
	
	public static void main(String[] args) {
		test01();
	}

	private static void test01() {
		// 학생객체를 받아서 java와 algo를 합친것을 반환
		Function<Student, Integer> function = t -> {
				return t.algo + t.java;
		};
		System.out.println(function.apply(new Student("대전 7반", 90, 95)));
	}
}

 

    - Operation : T XXX (T)

    - Predicate : boolean test(T)

 


 

10. 메서드 참조

package com.ssafy.day7.offline;

import java.util.Arrays;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.ToIntFunction;
import javax.security.auth.Subject;
import javax.xml.validation.Validator;

/*
 *	메서드 참조( :: )
 *	클래스 :: 정적메서드(static) 
 *	인스턴스객체 :: 인스턴스메서드
 *	클래스 :: 인스턴스메서드
 *	클래스 :: new (생성자) 
 */
public class LamdaTest07_MethodRef {

	static class Student {
		String name;
		int java;
		int algo;
		String result;

		public Student() {
		}

		public Student(String name, int java, int algo) {
			this.name = name;
			this.java = java;
			this.algo = algo;
		}

		public void info() {
			System.out.printf("%s의 정보 : java(%d), algo(%d)\n", name, java, algo);
		}
	}

	static class Converter {
		int[] makeArray(String data) {
			String[] array = data.split("-");
			int[] result = new int[array.length];
			int cur = 0;
			for (String v : array) {
				result[cur++] = Integer.parseInt(v);
			}
			return result;
		}
	}

	public static void main(String[] args) {
//		test01(); // 메서드 참조 : 클래스 메서드 참조
//		test02(); // 메서드 참조 : 인스턴스 메서드 호출
//		test03(); // 메서드 참조 : 파라미터 기준 인스턴스 메서드 호출
		test04(); // 메서드 참조 : 생성자 호출
	}

	static interface StudentFactory {
		Student createStudent(String name, int java, int algo);
	}

	private static void test04() {
		{
			StudentFactory factory = (name, java, algo) -> new Student(name, java, algo);
			Student student = factory.createStudent("김싸피", 99, 88);
			student.info();
		}
		{
			StudentFactory factory = Student :: new;
			Student student = factory.createStudent("김싸피", 99, 88);
			student.info();
		}
	}

	private static void test03() {
		{
			Consumer<Student> consumer = s -> s.info();
			consumer.accept(new Student("김싸피", 100, 90));
		}
		{
			// 클래스 :: 인스턴스메서드
			Consumer<Student> consumer = Student::info;
			consumer.accept(new Student("김싸피", 100, 90));
		}
	}

	private static void test02() {
		Converter converter = new Converter();
		{
			// 람다
			// 문자열을 받아서 int[] 변환
			Function<String, int[]> function = v -> converter.makeArray(v);
			int[] array = function.apply("10-11-9-10-2");
			System.out.println(Arrays.toString(array));
		}
		{
			// 메서드 참조 - 인스턴스 메서드 참조
			// 문자열을 받아서 int[] 변환
			Function<String, int[]> function = converter::makeArray;
			int[] array = function.apply("10-11-9-10-2");
			System.out.println(Arrays.toString(array));
		}
	}

	private static void test01() {
		{
			// 익명클래스
			ToIntFunction<String> converter = new ToIntFunction<String>() {
				public int applyAsInt(String value) {
					return 0;
				}
			};
		}
		{
			// consumer, Supplier, Function, Operator, Predicate (람다식)
			ToIntFunction<String> converter = value -> Integer.parseInt(value);
			int value = converter.applyAsInt("12345");
			System.out.println(value);
		}
		{
			// 메서드 참조 : 클래스 이름::정적메서드 <- 매개변수가 정적메소드의 파리미터로 입력된다.
			ToIntFunction<String> converter = Integer::parseInt;
			int value = converter.applyAsInt("12345");
			System.out.println(value);
		}
	}
}

'Web > JAVA' 카테고리의 다른 글

XML 파싱  (0) 2024.01.25
I/O, Stream  (1) 2024.01.24
예외 처리(exception handling)  (0) 2024.01.22
abstract class, Interface, generic  (0) 2024.01.19
데이터 은닉(Encapsulation), 다형성(Polymorphism), Singleton  (0) 2024.01.18