티스토리 뷰

JAVA

190717 Comparator, Comparing, Ramda

猫猫 2019. 7. 17. 10:30
반응형
package prj190717;

import java.util.*;

class Book{
	String author;
	String name;
	
	Book(String author, String name){
		this.author = author;
		this.name = name;
	}	
	
	void setAuthor(String author) {
		this.author = author;
	}
	void setName(String name) {
		this.name = name;
	}
	
	String getAuthor() {
		return author;
	}
	
	String getName() {
		return name;
	}
	
	@Override
    public String toString() {
        return author+" - "+name;
    }
	
}//bookclass end


public class ComparatorTest  {
	
	static List<Book> createExampleBooks() {	
		return Arrays.asList(
				new Book("가ㄴㄷ", "book1"), //book 클래스의 생성자
				new Book("다ㄷㄹ", "book5"),
				new Book("나ㄹㅁ", "book6"),
				new Book("마ㅁㅂ", "book2"),
				new Book("라ㅂㅅ", "book4")
				);	
		}
	static void withoutThenComparing() {
		List<Book> list = createExampleBooks();
		System.out.println("Before the sort : " + list);
		
//==============sort by author		
//		Collections.sort(list, Comparator.comparing(Book::getAuthor));
//		list.sort(Comparator.comparing(e-> e.getAuthor())); //book.getAuthor -> book.getAuthor를 비교한다. 
																							//자기자신과 비교하는것
//		Collections.sort(list, Comparator.comparing(e->e.getAuthor())); 
		
//===============sort by name		
//		Collections.sort(list, Comparator.comparing(Book::getName)); //클래스이름::getter 문법임 메서드참조
//		list.sort(Comparator.comparing(e-> e.getName())); //익명함수, 이게 더 깔끔
// 		Collections.sort(list, Comparator.comparing(e->e.getName())); //Name
		
		System.out.printf("After the Sort : %s\n ", list); 
	}
	
	static void withThenComparing() {
		List<Book> list = createExampleBooks();
		System.out.println("Before the sort : " + list);
		Collections.sort(list,Comparator.comparing(Book::getName)
			.thenComparing(Comparator.comparing(Book::getAuthor)));
		System.out.printf("After the Sort : %s\n ", list); 
	}

	public static void main(String[] args) {

//	
//		List<Book> list = createExampleBooks();//책List 생성 할것		
		System.out.println("== not using thenComparing==");
		withoutThenComparing();
		System.out.println("== using thenComparing==");
		withThenComparing();
		

//============================override 사용
//		System.out.println("Before the sort : " + list);
//		Collections.sort(list, new Comparator<Book>() { //(자동정렬) (정렬할 것, 옵션(익명클래스))
//			@Override
//			public int compare(Book b1, Book b2) {
////				return b1.getAuthor().compareTo(b2.getAuthor());	//b1과 b2의 저자를 비교해서 return //compareTo는 문자열 비교
//				return b1.getName().compareTo(b2.getName());    // b1과 b2의 책 이름을 비교해서 return			
//			}					
//		});
//		
//		System.out.printf("After the Sort : %s\n ", list);
	}//main end

}//class end
반응형

'JAVA' 카테고리의 다른 글

190807 java 컴이랑 하는 야구게임  (0) 2019.08.07
190716 Comparable 과 compareTo  (0) 2019.07.16
190716 람다식과 FunctionalInterface  (0) 2019.07.16
190716 람다식, arraylist 테스트  (0) 2019.07.16
190716 Enhancedfor 3중 배열  (0) 2019.07.16