https://www.hackerrank.com/challenges/python-lists/problem


python에는 switch 가 없다,

if , elif, else 문으로 해결해야한다.


Posted by 빨강토끼
,

[Link] 2017_03th

이야기 2017. 10. 11. 09:12
  1. 구글보다 요리였어 
    좋은 내용이긴한데... 
    "떠날수 있었던건 그 자리에 있었기 때문이다"는 사실이 더 부럽다.

  2. 나도 리모트로 일해보고 싶다. 
    원격근무를 시작하고 바뀐 삶 
    어느 원격근무 직장인의 고민 
    원격근무는 꿈같은 얘기? 이들 기업을 보라 
    하루 원격근무 체험기

  3. The Google Brain team — Looking Back on 2016 
    구글 브레인팀의 2016년 한해를 회고한 글입니다. 
    장차 저의 직장...쿨럭....

  4. Ask "How Do You Do Your Work?" To Engage Someone In Conversation 
    요즘에는 개발자모임후 네트워킹 시간같은걸 가지는 경우가 있는데, 처음보는 분들에게 말을 걸기가 참 어색하다. 
    대화하는 방법도 공부가 필요한것 같다. 
    물론 자신감이 더 중요하겠지만...

  5. 미래의 유망직종은 데이터 과학자라고 한다. 
    [IT열쇳말] 데이터과학 
    데이터과학에 입문하고 싶다면, 이곳부터

  6. 구글비전 - 이미지처리 구글API 
    예전에는 이미지처리에 관심이 있었는데 요즘에는 오히려 자연어처리에 관심이 더 생기고 있음. 
    CLOUD NATURAL LANGUAGE API 
    CLOUD TRANSLATION API

  7. (소프트웨어 엔지니어를 위한) 끝내주는 이력서를 쓰는 방법 
    이력서는 중요하다...

  8. 신학생이 소개하는 최강의 글쓰기 앱 – 스크리브너 
    맥에서 글쓰기 프로그램의 지존 스크리브너 의 사용법을 동영상과 함께 쉽게 설명한다.

  9. Read This Google Email About Time Management Strategy

    • 막연히 잡은 계획들은 지키기가 어려움. 구체적으로 시간과 장소를 정해놓아야 잘 지킬수 있다.
    • 시간을 관리(manage)하는 것보다 시간을 만드(make)는 방법으로 여유시간을 만들어 활용하라.
    • 일을 심플하게 만들고 처리하여 시간의 효율을 만들어라.
  10. 프로그래머의 경력을 말아먹는 12가지 방법 
    프로그래머로서 일하는 태도에 대한 이야기임


Posted by 빨강토끼
,

[Link] 2017_02th

이야기 2017. 10. 11. 09:11
  1. 영어공부하기 좋은 미드 TOP 10 
    논문쓰고나서 미드 많은 볼겁니다.

  2. 해외연수 없이 한국에서 영어 실력 높이기 
    주위 환경을 뉴욕같이 만들어라.

  3. 개발자 가이드 파이썬, 장단점을 파헤치다 
    요즘 파이썬으로 개인프로젝트를 한다고 하니 파이썬의 장단점을 쉽고 간단하게 알려달라는 질문을 받았다. 
    내가 감히 언어간의 장단점을 비교할 만한 수준이 아니라는 생각에 쉽고 편하게 정의해 놓은 글이 있어서 소개한다.

  4. 9 Steps To Stop Dreaming and Start Doing 
    몽상가를 넘어 꿈꾸는자가 되기 위한 지침들.

  5. 질문은 힘이 세다. 
    http://ppss.kr/archives/48428 
    https://news.samsung.com/kr/전문가-컬럼-질문은-힘이-세다

  6. 업무 생산성을 높이는 12가지 방법 
    너무도 당연한 이야기지만 너무도 당연히 안지켜지는....

    1. 7~9시간 정도로 충분히 자라.
    2. 일어나서 20분 정도 워밍업을 한후 출근하라.
    3. 적당한 양의 할일의 우선순위를 정하라.
    4. 힘이 없다? 운동을 해라.
    5. 카페인 섭취 줄여라.
    6. 때론 장소를 바꿔서 일해봐라.
    7. 멀티테스킹을 관리하라.
    8. 정리정돈을 해라.
    9. 정신적인 휴식시간을 가져라.
    10. 좋은 습관과 규칙을 가져라.
    11. 시간낭비 사이트를 피하라.
    12. 어려운일부터 해라.
  7. 한국은행 경제교육사이트 
    개발자도 경제에 대하여 알아야한다.

  8. 넷플릭스에 대하여 
    동영상으로 알기 쉽게 넷플릭스에 대하여 알려준다.

  9. 할일목록을 모두 다 마칠 수 없는 이유 
    할일목록이 남아있다는 것을 내가 무언가를 하고 있고 살아있다는 증거이다. 
    그러니 할일 목록을 최대한 심플한 방법으로 유지하며 스트레스를 받지 않는것이 중요하다.

  10. 자신이 컴퓨터 공학을 공부하는 이유가 무엇인지 알고 있나요? 

    100% 동의 하는건 아니지만 컴퓨터공학 전공 유무를 떠나서 한번 읽어볼만한 내용같음.


Posted by 빨강토끼
,

[Link] 2017_01th

이야기 2017. 10. 11. 09:10
  1. w3schools.com 
    w3schools는 프론트엔드쪽에 개발중 기본적인 언어나 기술에 대해서 잘설명되어있고 배울수있는 사이트같다. 
    개인적으로 나는 백엔드개발쪽으로 집중하는 과정이라서 아직 자세히 살펴보거나 공부하진 않고 있다. 
    그런데 최근 GDG DevFest Seoul 2016 의 발표중에 w3schools는 제발 그만 가라는 내용이 있어서 ... 
    https://festi.kr/festi/gdg-korea-2016-devfest-seoul/ (Boot Camp: 초보 개발자를 위한 웹 프론트엔드 개발 101) 
    참고로 자바스크립트를 좀더 "보안"적으로 작성하기 위하여 JavaScript 1.8.5 (ECMAScript version 5)부터 도입된 sctrict mode 에 대한 예제를 소개한다.http://www.w3schools.com/js/js_strict.asp

  2. 7 Key Differences Between Successful People And Unsuccessful People 

    성공하는 사람과 성공하지 못하는 사람의 7가지 차이점. 
    성공하는 사람과 성공하지 못하는 사람은 많은 점에서 차이가 있다고 합니다. 
    조만간 부족한 실력이지만 번역글을 별도로 올려봐야겠다.

  3. 5 Workout Infographics For You To Exercise At Home On Weekdays 
    주중에 집에서 할수있는 5가지 운동.

  4. 연령별 돈에 대한 실수 
    11 Common Money Mistakes People Make in Their 40s 
    6 Common Money Mistakes People Make in Their 30s 
    10 Common Money Mistakes Among 20-Somethings: Are You Making Them? 
    10 Common Money Mistakes People Wish They Realized In Their 20s

  5. [오픈소스] 평범한 개발자가 리눅스 커널에 참여하게된 이야기 - 행사 후기 및 의견

  6. 프로그래머 추천 영화 
    "환상이 아닌 현실을 그리다" IT를 99.8% 정확하게 묘사한 영화 9선 
    프로그래머를 위한 최고의 영화 (개발자에게 영감을 주는 영화) 
    몇개는 본것 같다.

  7. 서재포르노(?) 
    책덕후들의 사이트. 말 그대로 책들이 모여있거나 도서관 서재 등의 사진이 모여있다. 나도 언젠가는 넓은 집에 거실 이나 책방을 이렇게 꾸미고 싶다... (헉헉헉...)

  8. Best Honeymoon Destinations You Should Not Miss 
    와이프랑 이런곳 여행다니고 싶다.

  9. If You Aren't Taking Notes, You Aren't Learning 
    적자생존. 적고 기록하는 사람이 성공한다.

  10. 소프트웨어 개발자의 나아갈 길 
    감독이나 코치가 아닌 계속 현역선수로써 소프트웨어 개발자를 유지하고 발전시키기 위해 나아갈 길을 제시한다.


Posted by 빨강토끼
,

link_2016_01th

이야기 2017. 10. 11. 09:09
  1. 미래에는 누구나 쉽게 코딩을 할 수 있는 소프트웨어 엔지니어가 될거다

  2. Women Techmakers Mountain View Summit 2016: 기조연설 
    흰 코끼리 기회 
    많은 생각을 하게되는 발표이다.

  3. Women Techmakers Mountain View Summit 2016: 페널대화 
    여성리더들의 사업을 시작하게된 동기와 성공 팁, 자기관리, 조직관리등 비단 여성뿐만 아니고 모든 분들이 봐도 자기발전에 도움이 되는 이야기들을 들을 수 있음.

  4. Women Techmakers New York Summit 2016: Women Creating Opportunities in Tech 
    기회를 만드는 법 (How to create opportunity)

    • 손을 들어라
    • 질문을 해라
    • 문을 두드려라 (문을 열어라).
    • 적어라.
    • 틀리거나 내가 못하는게 아니다. 단지 익숙하지 못할뿐이다.
    • 모두가 들을수 있게 크고 자신있게 (꿈을) 말하라
    • 그외 좋은 얘기를 많이 들을 수 있다. 강추
  5. Books Programmers Don't Really Read 
    꼭 읽어봐야겠다.

  6. 고품질코딩 방법 
    http://www.informit.com/articles/article.aspx?p=2223710 
    https://code.tutsplus.com/tutorials/top-15-best-practices-for-writing-super-readable-code--net-8118 
    http://softwareengineering.stackexchange.com/questions/61655/how-do-you-know-youre-writing-good-code

  7. 각종 String 및 text 작업을 도와주는 웹사이트 
    이러한 작업을 많이 하는 직종에서는 정말 편할듯. 
    나도 이런 사이트 만들어보면 공부가 많이 될것 같다. 
    http://www.text-utils.com/

  8. 알고리즘 
    알고리즘 대회에 필요한 수학

  9. Y분에 X를 배우다. 
    짧은 시간에 간단히 다양한 언어에 대해 가르쳐주는 사이트이다. 
    잼있다. (한글도 있음) 
    Learn X in Y minutes

  10. 웹 프레임워크 
    프론트엔드 개발자분들에게 기술습득에 유용한 사이트 & 커뮤니티 & 배울(On/Off) 수 있는 사이트인것 같다. 
    http://webframeworks.kr/


Posted by 빨강토끼
,

As-Is (데이터 컬렉션 반복을 명시적으로 관리하는 외부 반복을 수행)

List<Dish> vegetarianDishes = new ArrayList<>();  
for(Dish d : menu){  
  if(d.isVegetarianDishes()){
    vegetarianDishs.add(d);
  }
}

To-Be (filter와 collect 연산을 지원하는 스트림 API를 이용해서 데이터 켈렉션 반복을 내부적으로 처리)

List<Dish> vegetarianMenu = menu.stream()  
            .filter(Dish::isVegetarian)
            .collect(toList());
System.out.println(vegetarianMenu.toString());  

5.1 Filtering and Slicing

5.1.1 Filtering with a predicate

stream 인터페이스는 filter 기능을 지원한다. predicate 를 파라미터로 받아서 필터링된 요소들을 stream 형식으로 반환한다.

List<Dish> vegetarianMenu = menu.stream()  
            .filter(Dish::isVegetarian) // 채식에 가까운 Dish 인지 여부
            .collect(toList());
System.out.println(vegetarianMenu.toString());  

5.1.2 Filtering unique elements

고유한 요소를 반환하는 distinct 함수를 제공한다.

List<Integer> numbers = Arrays.asList(1,2,1,3,3,2,4);  
numbers.stream()  
      .filter(i -> i%2 == 0)
      .distinct()
      .forEach(System.out::println);

5.1.3 Truncating a stream

반환되는 요소의 갯수를 제한 할 수 있는 limit(n) 함수를 제공한다. 그 이외의 요소들은 처리되지 않는다.

List<Dish> dishes = menu.stream()  
             .filter(d -> d.getCalories() > 300)
             .limit(3)
              .collect(toList());
System.out.println(dishes.toString());  

5.1.4 Skipping elements

skip(n)은 n만큼의 요소를 제외한 나머지를 반환하는 함수이다. limit(n)과는 상호보완적인 관계이다.

List<Dish> dishes = menu.stream()  
            .filter(d -> d.getCalories() > 300)
            .skip(2)
            .collect(toList());
System.out.println(dishes.toString());  

Quiz 5.1 처음 2개의 고기요리를 고르시오.

List<Dish> dishes =  
            menu.stream()
            .filter(d -> d.getType() == Dish.Type.MEAT)
            .limit(2)
            .collect(toList());
System.out.println(dishes.toString());  

5.2 Mapping

stream은 SQL 의 select 문 처럼 stream에서 특정 컬럼을 추출하는 함수를 제공한다(map, flatMap).

5.2.1 map

map 는 함수를 인수로 받는 메소드이다. 인수로 받은 함수를 stream의 매 요소에 적용되어 새로는 stream을 생성한다.

List<String> dishNames =  
            menu.stream()
            .map(Dish::getName)
            .collect(toList());
System.out.println(dishNames);  

Dish.getName()의 리턴타입이 String 이기 때문에 map메소드의 리턴타입 역시 Stream\

아래의 경우에는 String.length() 의 리턴타입이 Integer이므로 map메소드의 리턴타입은 Stream\

List<String> words = Arrays.asList("Java8", "Lambdas", "In", "Action");  
List<Integer> wordLenghs = words.stream()  
            .map(String::length)
            .collect(toList());
System.out.println(wordLenghs);  

그러면, 메뉴의 각 요리이름을 구한 후 그 이름들의 길이를 구하고 싶다면 아래와 같이 할 수 있다.

List<Integer> dishNameLengths = menu.stream()  
            .map(Dish::getName)
            .map(String::length)
            .collect(toList());
System.out.println(dishNameLengths);  

만일 단어의 목록에서 유일한 문자들(unique characters)을 추출하려면 (예를 들어 ["Hello","World"] 라는 list 가 있다면,

["H", "e", "l", "o", "W", "r", "d"] 라는 리턴을 원한다면) 아래와 같이 코딩이 가능할 것 이다.

List<String> hello = Arrays.asList("Hello", "World");  
List<String[]> uniqueWord = hello.stream()  
            .map(word -> word.split(""))
            .distinct()
            .collect(toList());
System.out.println(uniqueWord.get(0)[0]);  

하지만 리턴값으로 원하는것이 Stream\<string[]> 이 아니고 Stream\

이 과정을 차례대로 따라가 보자.

Attempt using Arrays.stream and flatMap

먼저, 배열의 stream대신 문자들의 stream이 필요하다. Arrays.stream()은 배열을 받아 stream으로 처리한다.

String[] arrayOfWords = {"Goodbye", "World"};  
Stream<String> streamOfWords = Arrays.stream(arrayOfWords);  

flatMap은 Arrays.stream()을 통해 여러개로 나눠진 stream들을 하나로 모아 새로운 stream 을 생성한다.

방금 전 예제에 적용해보자

List<String> hello = Arrays.asList("Hello", "World");  
    List<String> words = hello.stream()
            .map(word -> word.split(""))
            .flatMap(Arrays::stream)
            .distinct()
            .collect(toList());
    System.out.println(words);

output :  
[H, e, l, o, W, r, d]

그림으로 비교해 보면 아래와 같다.

vs.

Quiz 5-2

1.Give a list of numbers, how would you return a list of the square of each number? For example, given [1,2,3,4,5] you should return [1,4,9,16,25].

   List<Integer> num = Arrays.asList(1,2,3,4,5);
   List<Integer> powNUm = num.stream()
            .map(n -> n*n)
            .collect(toList());
   System.out.println(powNUm);

   output :
   [1, 4, 9, 16, 25]

2.Given two lists of numers, how would you return all pairs of numbers? For example given a list [1,2,3] and a list[3,4] you should return [(1,3), (1,4), (2,3), (2,4), (3,3), (3,4)]. For simplicity, you can represent a pair as an array with elements.

   List<Integer> num1 = Arrays.asList(1,2,3);
   List<Integer> num2 = Arrays.asList(3,4);
   List<int[]> pairs = num1.stream()
               .flatMap(i -> num2.stream().map(j -> new int[]{i,j}))
               .collect(toList());
   pairs.forEach(pair -> System.out.println(pair[0]+","+pair[1]));

   output :
   1,3
   1,4
   2,3
   2,4
   3,3
   3,4

3.How would you extend the previous example to return only pairs whose sum is divisible by 3? For example,(2,4) and (3,3) are valid.

   List<Integer> num1 = Arrays.asList(1,2,3);
   List<Integer> num2 = Arrays.asList(3,4);
   List<int[]> pairs = num1.stream()
                           .flatMap(i -> num2.stream()
                           .filter(j -> (i+j)%3 == 0)
                           .map(j -> new int[]{i,j}))
               .collect(toList());
   pairs.forEach(pair -> System.out.println(pair[0]+","+pair[1]));

   output :
   2,4
   3,3

5.3 Finding and matching

stream의 요소들이 주어진 속성에 일치여부를 찾을 수 있는 기능을 제공한다.(allMatch, anyMatch, noneMatch, findFirst, findAny)

5.3.1 Checking to see if a predicate matches at least one element

anyMatch 는 stream의 요소중에 주어진 속성과 일치하는 것이 하나라도 있으면 true를 리턴한다. terminal operation이다.

if(menu.stream().anyMatch(Dish::isVegetarian)){  
  System.out.println("The menu is (somewhat) vegetarian friendly!!");
}

5.3.2. Checking to see if a predicate matches all elements

anyMatch 는 stream의 요소 모두가 주어진 속성과 일치하면 true를 리턴한다. terminal operation이다.

boolean isHealthy = menu.stream()  
                        .allMatch(d -> d.getCalories() < 1000);

allMatch의 반대가 nonMatch 이다. 모든요소가 주어진 속성과 일치하지 않으면 true를 리턴한다.

boolean isHealthy = menu.stream()  
                        .noneMatch(d -> d.getCalories() => 1000);

anyMatch, allMatch, noneMatch 이 3개의 기능을 short-circuiting 이라고 한다.

short-circuiting 이란

...

5.3.3. Finding an element

findAny 메소드는 임의의 요소를 반환한다. 이것은 다른 stream 기능과 결합하여 사용된다. filter 와 findAny를 통해서 채식요리를 찾을 수 있다.

Optional<Dish> dish =  
            menu.stream()
            .filter(Dish::isVegetarian)
            .findAny();
System.out.println(dish.toString());  

간단히 Optional 알아보기(chapter 10. p315)

Optional\

null이 반환될때 생길 수 있는 문제를 피하기 위하여 java8에서는 Optional이 소개되었고 자세한 설명은 chapter10에 있다.

여기서는 제공되는 메소드에 대한 간략한 설명을 한다.

  • isPresent() : Optional이 값을 포함하고 있다면 true, 아니면 false를 리턴한다.
  • ifPresnet(Consumer\
  • T get() : 값이 있으면 값을 리턴하고 없으면 NoSuchElement-Exception을 발생시킨다.
  • T orElse(T other) : 값이 있으면 값을 리턴하고 없으면 기본값을 리턴한다.

5.3.4. Finding the first element

findFirst 는 findAny와 비슷하지만, steam의 요소의 순서를 보장한다는 차이점이 있다.

List에서 3으로 나눠지는 제곱값을 찾는 경우

List<Integer> someNumbers = Arrays.asList(1,2,3,4,5);  
Optional<Integer> firstSquareDivisibleByThree =  
            someNumbers.stream()
            .map(x -> x*x)
            .filter(x -> x%3 == 0)
            .findFirst();
System.out.println(firstSquareDivisibleByThree);  

findAny 와 findFirst를 구분한 이유는 findAny는 병렬처리시 순서를 보장할 수 없기 때문이다.

5.4. Reducing

메뉴의 모든 요리의 칼로리를 더한 값은?

가장 칼로리가 높은 음식은?

reducton operations은 stream을 Integer같은 하나의 값으로 합칠 수 있는 메소드를 제공한다.

5.4.1 Summing the elements

// 모든 요소를 더한 값 
int sum = numbers.stream().reduce(0, (a,b) -> a+b);  
2개의 인수  
- 초기값 . 예) 0
- 2개의 요소를 합치고 계산하는 구문 예) (a,b) -> a+b.

// 모든 요소를 곱한 값
int product = numbers.stream().reduce(1, (a,b) -> a*b);  

그림으로 표현하면 위와 같다.

아래와 같이 좀 더 간소하게 표현할 수 있음.

List<Integer> numbers = Arrays.asList(1,2,3,4,5);  
int sum1 = numbers.stream().reduce(0, Integer::sum);  
System.out.println(sum1);

//Optional<Integer> sum2 = numbers.stream().reduce((a,b) -> (a+b));
Optional<Integer> sum2 = numbers.stream().reduce(Integer::sum);  
System.out.println(sum2);  

5.4.2. Maximum and minimum

stream에서 최대값과 최소값을 구할수 있다.

Optional<Integer> max = numbers.stream().reduce(Integer::max);  
Optional<Integer> min = numbers.stream().reduce(Integer::min); // (x,y) -> x<y?x:y  

Quiz 5-3 : reducing

How would you count the number of dishes in a stream using the map and reduce method?

int count = menu.stream()  
            .map(d-> 1)
            .reduce(0, (a,b) -> a+b);
System.out.println(count);  

or

long count = menu.stream().count();  

Benefit of the reduce method and parallelism

reduce를 사용하면 내부반복이 추상화되면서 내부 구현에서 병렬로 reduce를 실행 할 수 있음.

반면에 반복적인 합계(iteractive summation)에서는 sum 변수를 공유해야 하므로 병렬로 구현하는게 힘들고, 강제적으로 동기화 하더라도 스레드간의 경쟁으로 이득이 감소하게 된다.

7장에서는 fork/join 프레임워크를 이용하는 방법을 보게 될거지만 중요한 사실은 가변 누적자 패턴(mutable accumulator pattern)은 병렬화의 막다른 골목이다는 것이다. 그러므로 reduce 라는 새로운 패턴이 필요하게 되었다.

7장에서 stream의 모든 요소를 병렬로 더하는 코드를 방법을 배우게 된다.

int sum = numbers.parallelStream().reduce(0, Integer::sum);  

Stream operations : stateless vs. stateful

map, filter 등 : 입력 스트림에서 각 요소를 받아 0 또는 결과를 출력 스트림으로 보내기 때문에 내부 상태를 갖지 않는 연산(stateless operation)

reduce , sum, max 등 : 결과를 누적할 내부 상태가 필요하지만 스트림에서 처리하는 요소 수와 관계없이 내부 상태의 크기는 한정(bounded) 되어 있음.

반면 sorted, distinct 등 : filter 나 map 처럼 스트림을 입력으로 받아 다른 스트림을 출력하는 것처럼 보이지만, 다르다. 스트림의 요소를 정렬하거나 중복을 제거하려면 과거의 이력을 알고 있어야 한다. 예를 들어 어떤 요소를 출력 스트림으로 추가하려면 모든 요소가 버퍼에 추가되어 있어야 한다. 연산을 수행하는 데 필요한 저장소 크기는 정해져있지 않으므로 데이터 스트림의 크기가 무한이라면 문제가 생각 수 있다. 따라서 이러한 연산은 내부 상태를 갖는 연산(stateful operation)으로 간주.

연산형식반환 형식사용된 함수명함수 디스크립터
filter중간 연산Stream<t>< td="">Predicate<t>< td="">T -> boolean
distinct중간 연산 (상태 있는 언바운드)Stream<t>< td="">
skip중간 연산 (상태 있는 언바운드)Stream<t>< td="">Long
limit중간 연산 (상태 있는 언바운드)Stream<t>< td="">Long
map중간 연산Stream<r>< td="">Function<t, r><="" td="">T -> R
flatMap중간 연산Stream<r>< td="">Function<t, stream<r>><="" td="">T -> Stream<r>< td="">
sorted중간 연산 (상태 있는 언바운드)Stream<t>< td="">Comparator<t>< td="">(T, T) -> int
anyMatch최종 연산booleanPredicate<t>< td="">T -> boolean
noneMatch최종 연산booleanPredicate<t>< td="">T -> boolean
allMatch최종 연산booleanPredicate<t>< td="">T -> boolean
findAny최종 연산Optional<t>< td="">
findFirst최종 연산Optional<t>< td="">
forEach최종 연산voidConsumer<t>< td="">T -> void
collect최종 연산RCollector<t, a,="" r><="" td="">
reduce최종 연산 (상태 있는 언바운드)Optional<t>< td="">BinaryOperator<t>< td="">(T, T) -> T
count최종 연산long

5.5. 실전 연습

public class Trader {  
  private final String name;
  private final String city;

  public Trader(String n, String c){
    this.name = n;
    this.city = c;
  }

  public String getName() {
    return name;
  }

  public String getCity() {
    return city;
  }

  @Override
  public String toString() {
    return "practice.Trader:" + this.name + " in " + this.city;
  }
}

public class Transaction {  
  private final Trader trader;
  private final int year;
  private final int value;

  public Transaction(Trader trader, int year, int value) {
    this.trader = trader;
    this.year = year;
    this.value = value;
  }

  public Trader getTrader() {
    return trader;
  }

  public int getYear() {
    return year;
  }

  public int getValue() {
    return value;
  }

  @Override
  public String toString() {
    return "{" + this.trader + ", " +
            "year: " + year + ", " +
            "value: " + value + "}";
  }
}


Trader raoul = new Trader("Raoul", "Cambridge");  
Trader mario = new Trader("Mario", "Milan");  
Trader alan = new Trader("Alan", "Cambridge");  
Trader brian = new Trader("Brian", "Cambridge");

List<Transaction> transactions = Arrays.asList(  
          new Transaction(brian, 2011, 300),
          new Transaction(raoul, 2012, 1000),
          new Transaction(raoul, 2011, 400),
          new Transaction(mario, 2012, 710),
          new Transaction(mario, 2012, 700),
          new Transaction(alan, 2012, 950)
);

1.2011년에 일어난 모든 트랜잭션을 찾아 값을 오름차순으로 정리하시오.

   List<Transaction> ordredTran2011 =
               transactions.stream()
               .filter(d -> d.getYear() == 2011)
               .sorted(Comparator.comparing(Transaction::getYear))
               .collect(toList());
   System.out.println(ordredTran2011);

2.거래자가 근무하는 모든 도시를 중복 없이 나열하시오.

3.케임브리지에서 근무하는 모든 거래자를 찾아서 이름순으로 정렬하시오.

4.모든 거래자의 이름을 알파벳순으로 정렬해서 반환하시오.

5.밀리노에 거래자가 있는가?

6.케임브리지에 거주하는 거래자의 모든 트랜잭션값을 출력하시오.

7.전체 트랜잭션 중 최댓값은 얼마인가?

8.전체 트랜잭션 중 최솟값은 얼마인가?

5.6. 숫자형 스트림

5.6.3. 숫자 스트림 활용: 피타고라스 수

Stream<double[]> pythagoreanTriples2 =  
            IntStream.rangeClosed(1,100).boxed()
            .flatMap(a ->
            IntStream.rangeClosed(a,100)
            .mapToObj(
                    b -> new double[]{a, b, Math.sqrt(a*a+b*b)})
                    .filter(t -> t[2]%1 == 0));
    pythagoreanTriples2.limit(5)
            .forEach(t ->
            System.out.println(t[0] + ", " + t[1] + ", " + t[2]));

output :  
3.0, 4.0, 5.0  
5.0, 12.0, 13.0  
6.0, 8.0, 10.0  
7.0, 24.0, 25.0  
8.0, 15.0, 17.0  

5.7. 스트림 만들기

5.7.1. 값으로 스트림 만들기

Stream<String> stream = Stream.of("Java 8 ", "Lambdas ", "In ", "Action");  
stream.map(String::toUpperCase).forEach(System.out::println);

output :  
JAVA 8  
LAMBDAS  
IN  
ACTION  

5.7.2. 배열로 스트림 만들기

int[] numbers = {2, 3, 5, 7, 11, 13};  
int sum = Arrays.stream(numbers).sum();  
System.out.println(sum);

output :  
41  

5.7.3. 파일에서 스트림 만들기

long uniqueWords = 0;

try(Stream<String> lines =  
    Files.lines(Paths.get("/Users/red/pro/java8/out/production/ch5/data.txt"), Charset.defaultCharset())){
    uniqueWords = lines.flatMap(line -> Arrays.stream(line.split(" ")))
              .distinct()
              .count();
}
catch(IOException e){  
  e.printStackTrace();
}
System.out.println(uniqueWords);  

Quiz. Fibonacci Tuples

Stream.iterate(new int[]{0,1}, t -> new int[]{t[1], t[0]+t[1]})  
            .limit(20)
            .forEach(t -> System.out.println("("+ t[0] + ","+ t[1] + ")"));


Posted by 빨강토끼
,

chapter 4. Introducing streams

4.1 What are Streams

  • 마치 SQL 쿼리 같이 데이터를 처리
  • 많은 요소를 포함하는 커다란 컬렉션을 단순히 처리

Before(Java 7)

List<Dish> lowCaloricDishes = new ArrayList<>();  
for(Dish d: menu){  
  if(d.getCalories() < 400){
    lowCaloricDishes.add(d);
  }
}

Collections.sort(lowCaloricDishes, new Comparator<Dish>() {  
  @Override
  public int compare(Dish d1, Dish d2) {
    return Integer.compare(d1.getCalories(), d2.getCalories());
  }
});

List<String> lowCaloricDishesName = new ArrayList<>();  
for(Dish d: lowCaloricDishes){  
  lowCaloricDishesName.add(d.getName());
}

자바8 코드

List<String> lowCaloricDishesName =  
  menu.stream()
  //menu.parallelStream()
  .filter(d -> d.getCalories() < 400)
  .sorted(Comparator.comparing(Dish::getCalories))
  .map(Dish::getName)
  .collect(toList());

4.2 Getting started with streams

  • Sequence of elements

    • Collections are about data

    • streams are about computations

  • Source
    • 정렬된 컬렉션으로 스트림을 생성하면 정렬이 그대로 유지된다. 즉 리스트로 스트림을 만들면 스크림의 요소는 리스트의 요소와 같은 순서를 유지한다.
  • Data processing operations
    • 함수형 프로그래밍 언어에서 일반적으로 지원하는 연산과 데이터베이스와 비슷한 연산을 지원
    • 예) filter, map, reduce, find, match, sort 등
    • 스트림연산은 순차적으로 또는 병렬로 실행될 수 있다.

In addition

  • Pipelining
    • 스트림 연산 끼리 연결하여 커다란 파이프라인을 구성 할 수 있음.
    • 게으름(laziness), 쇼트서킷(sort-cicuiting) 같은 최적화를 얻을 수 있음.
    • 데이터베이스의 SQL 쿼리 와 비슷
  • Internal iteration
    • 반복자를 이용해서 명시적으로 반복하는 컬렉션과 달리 스트림은 내부 반복을 지원
List<String> threeHightCaloricDishNames =  
            menu.stream()
            .filter(d -> d.getCalories() > 300)
            .map(Dish::getName)
            .limit(3)
            .collect(toList());
  • filter

    • 람다를 인수로 받아 스트림에서 특정 요소를 제외

    filter(d -> d.getCalories() > 300)

  • map

    • 람다를 이용해서 한 요소를 다른 요소로 변환하거나 정보를 추출

    map(Dish::getName)

  • limit

    • 정해진 개수 이상을 추출 못하게 한계를 지정

    limit(3)

  • collect

    • 스트림을 다른 형식으로 변환

    collect(toList());

4.3 Streams vs. Collections

  • DVD vs. Internet stream
  • 모든 값을 메모리에 저장하여 계산 vs. 필요할때만 요소를 계산
  • 브라우저 인터넷 검색

  • Traversavle only once

  List<String> title = Arrays.asList("java8", "In", "Action");
      Stream<String> s = title.stream();
      s.forEach(System.out::println);
      s.forEach(System.out::println);

  output :
  java8
  Exception in thread "main" In
  Action
  java.lang.IllegalStateException: stream has already been operated upon or closed
      at java.util.stream.AbstractPipeline.sourceStageSpliterator(AbstractPipeline.java:274)
      at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580)
      at Solution.IllegalStateException(Solution.java:77)
      at Solution.main(Solution.java:102)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:497)
      at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
  • External vs. internal iteration

    for-each loop

  List<String> names = new ArrayList<>();
  for(Dish d: menu){
    names.add(d.getName());
  }

iterator

  List<String> names = new ArrayList<>();
  Iterator<String> iterator = menu.iterator();
  while(iterator.hasNext()){
    Dish d = iterator.next();
    names.add(d.getName());
  }

stream: internal iteration

  List<String> names = menu.stream()
                           .map(Dish::getName)
                           .collct(toList());

4.4 Stream operations

  • intermediate operations

  • terminal operations

  • Intermediate operations

    • 다른 intermediate operations 와의 상호연동을 통하여 pipe line 을 형성한다.
    • intermediate operations의 동작들이 하나의 terminal operations으로 모이기 때문에 terminal operations이 호출되어서 파이프라인이 시작하기전 까지의 흐름이 동작하지 않는다( lazy)
    • 파이프라인이 어떻게 동작되고 있는지 확인하기 위하여 각각의 람다함수에 print 문을 삽입한다.(이러한 코딩은 흔히 사용되지 않지만 배우는 과정이기 때문에 특별한 경우이다.)
  List<String> names =
              menu.stream()
              .filter(d -> {
                System.out.println("filtering " + d.getName());
                return d.getCalories() > 300;
              })
              .map(d -> {
                System.out.println("mapping " + d.getName());
                return d.getName();
              })
              .limit(3)
              .collect(toList());
      System.out.println(names);


  filtering pork
  mapping pork
  filtering beef
  mapping beef
  filtering chicken
  mapping chicken
  [pork, beef, chicken]
  1. 칼로리가 300보다 큰 dish 중에 오직 3개만 추출하고 동작이 끝난다.(Short-circuitinge)
  2. filter 와 map 의 명령이 하나의 경로로 합쳐져서 동작한다.(loop fusion)

    • Terminal operations
  3. Stream pipe 로의 결과를 처리한다.

  4. List 나 Integer, 혹은 void 등의 스트림이 아닌 다양한 포맷으로 데이터를 변환하여 리턴한다.

    menu.stream().forEach(System.out::println);

    • Working with streams
  5. Builder pattern 과 비슷

  6. intermediate operations
    • filter
    • map
    • limit
    • sorted
    • distinct
  7. Terminal operations
    • forEach
    • count
    • collect

Summary

  • stream은 데이터처리동작을 지원하는 source에서 연속된 요소이다.
  • Stream은 내부반복을 사용한다.
  • intermediate 와 terminal operations 이 있다.
  • intermediate operations 은 filter와 map 등 stream을 반환하고 다른 stream와 연동된다. 파이프라인이 설정될뿐 어떤 result 동작을 하지 않는다.
  • forEach 와 같은 terminal operations 은 스트림이 아닌 결과를 리턴한다.
  • 스트림의 요소는 요청시에 계산된다.


Posted by 빨강토끼
,

특정 한달 간의 날짜 출력

SELECT TO_CHAR(TO_DATE('20160701','yyyymmdd') + LEVEL - 1, 'yyyymmdd') AS DAY  
FROM DUAL  
CONNECT BY LEVEL <= ADD_MONTHS(TO_DATE('201607','yyyymm'),1) - TO_DATE('201607','yyyymm');  

1~30 까지 출력 
SELECT LEVEL 
FROM DUAL 
CONNECT BY LEVEL <= 30;

Posted by 빨강토끼
,

기존의 Maven 으로 작성된 프로젝트를 Gradle 로 변경하는 작업을 하였다.

자신있게 gradle build 를 했다.

그런데 Maven 으로 잘되던 것이 갑자기 test step 에서 error 가 나는것이다.

이유는 
import static org.hamcrest.CoreMatchers.containsString; 
에서 containsString 을 못찾는것이다.

이유를 찾아보니 
JUnit 에 종속적인 hamcrest 의 org.hamcrest 와 
org.mockito에 있는 org.hamcrest 가 충돌나는 것이었다.

정확한 해결책인지는 아직도 확신은 안들지만 
아래같은 순서로 [프로젝트네임].gradle 파일의 내용을 수정하니 잘되었다.

dependencies {  
  testCompile group: 'org.hamcrest', name: 'hamcrest-core', version: '1.3'
  testCompile group: 'org.mockito', name: 'mockito-all', version:'1.10.19'
  testCompile group: 'junit', name: 'junit', version:'4.12'
}

아마도 dependencies 하는 순서대로 호출시 참조하는 것 같다.

Posted by 빨강토끼
,

나는 java 에서 배열을 shift 하는 방법이 가끔 헛갈릴때가 있다.

그중 rotation left 하는 방법을 정리하였다.

그런데 이 방법은 메모리를 주어진 배열의 2배를 사용한다. 주어진 배열만큼의 배열을 하나 더 생성하여서 옮겨진(rotation left) 위치에 copy를 하는 방식이다.

좀 더 효율을 높히기 위하여 생각할수있는 방법은 크게 2가지이다.

  1. 메모리 사용을 줄이기 위하여 직접 in-place 방법으로 처리하는 방식
  2. 속도를 높히기 위해서 하나하나를 copy하는 방식이 아닌 block단위로 copy하는 방식

1번 소스

2번 소스

Posted by 빨강토끼
,