반응형
package com.daonstar.web;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;



public class ListToMapTest {
	
	private List<Book> books;
	private final String NAME = "책읽자";
	private final int RELEASE_YEAR = 2009;
	private final String ISBN = "0101234929";
	private final int initAddBookCount = 3;
	
	@Before
	public void init() {
		System.out.println("@Before");
		books = new ArrayList<>();
		booksAdds();
	}
	
	@After
    public void tearDown() throws Exception {
		System.out.println("@After");
		books.clear();
    }

	private void booksAdds() {
		for (int i = 0; i < initAddBookCount; i++) {
			
			int releaseYear = RELEASE_YEAR;
			if ( i > 1 ) {
				releaseYear = RELEASE_YEAR + i;
			}
			books.add(new Book(NAME + i, releaseYear, ISBN + i));
		}
	}
	
	private Map<String, String> listToMap(List<Book> books) {
		return books.stream().collect(Collectors.toMap(Book::getIsbn,  Book::getName));
	}

	@Test
	public void whenConvertFromListToMap() {
		System.out.println("@test1");
		assertTrue(listToMap(books).size() ==3);
	}
	
	public Map<Integer, Book> listToMapWithDupKeyError(List<Book> books) {
		return this.books.stream().collect(Collectors.toMap(Book::getReleaseYear,  Function.identity()));
	}
	
	
	@Test(expected = IllegalStateException.class)
	public void whenMapHasDuplicateKey_whthout_merge_function_then_runtime_exception() {
		listToMapWithDupKeyError(books);
	}
	
	public Map<Integer, Book> listToMapWithDupKey(List<Book> books) {
		return books.stream().collect(Collectors.toMap(Book::getReleaseYear,  Function.identity(), (existing, replacement) -> existing));
	}
	
	@Test
	public void whenMapHasDuplicateKeyThenMergeFunctionHandlesCollision() {
		Map<Integer, Book> booksByYear = listToMapWithDupKey(books);
		assertEquals(2, booksByYear.size());
		assertEquals(ISBN + 0, booksByYear.get(RELEASE_YEAR).getIsbn());
	}
	
	public Map<Integer, Book> listToConcurrentMap(List<Book> books) {
		return books.stream().collect(Collectors.toMap(Book::getReleaseYear,  Function.identity(), (o1, o2) -> o1, ConcurrentHashMap::new));
	}
	
	@Test
	public void whenCreateConcurrentHashMap() {
		assertTrue(listToConcurrentMap(books) instanceof ConcurrentHashMap);
	}
	
	
	public TreeMap<String, Book> listToSortedMap(List<Book> books) {
		return books.stream()
				.sorted(Comparator.comparing(Book::getName))
				.collect(Collectors.toMap(Book::getName, Function.identity(), (o1, o2) -> o1, TreeMap::new));
	}
	
	@Test
	public void whenMapisSorted() {
		String firstBookName = "책읽자0";
		assertTrue(listToSortedMap(books).firstEntry().getKey().equals(firstBookName));
	}
	
	
}

 

나름 TDD하면서 해봤다.

아직  JUnit도 어설퍼서 이것저것 태스트 하느라 로그도 찍었다.

Collectors.toMap 요놈 이용해서 리스트를 맵으로 바꾸면 되는 요지인데, 키 중복일때 처리 방법도 있다.

요지는 list to map 인데 테스트 관련해서 리팩토링 할려고 노력중이라 코드가 산으로 가고 다른 생각이 많이 든다.

 

참고 https://www.baeldung.com/java-collectors-tomap

 

Java 8 Collectors toMap | Baeldung

Learn how to use the toMap() method of the Collectors class.

www.baeldung.com

 

반응형

+ Recent posts