Skip to content

*1단계 - 스트림, 람다, Optional 구현 #1696

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/main/java/nextstep/fp/Conditional.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package nextstep.fp;

public interface Conditional {
boolean test(Integer number);
}
10 changes: 10 additions & 0 deletions src/main/java/nextstep/fp/Lambda.java
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,14 @@ public static int sumAllOverThree(List<Integer> numbers) {
}
return total;
}

public static int sumAllConditional(List<Integer> numbers, Conditional conditional) {
int total = 0;
for (int number : numbers) {
if (conditional.test(number)) {
total += number;
}
}
return total;
}
}
21 changes: 13 additions & 8 deletions src/main/java/nextstep/fp/StreamStudy.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

Expand All @@ -15,19 +16,20 @@ public static long countWords() throws IOException {
.get("src/main/resources/fp/war-and-peace.txt")), StandardCharsets.UTF_8);
List<String> words = Arrays.asList(contents.split("[\\P{L}]+"));

long count = 0;
for (String w : words) {
if (w.length() > 12) count++;
}
return count;
return words.stream()
.filter(word -> word.length() > 12)
.count();
}

public static void printLongestWordTop100() throws IOException {
String contents = new String(Files.readAllBytes(Paths
.get("src/main/resources/fp/war-and-peace.txt")), StandardCharsets.UTF_8);
List<String> words = Arrays.asList(contents.split("[\\P{L}]+"));

// TODO 이 부분에 구현한다.
words.stream()
.filter(word -> word.length() > 12)
.sorted(Comparator.comparing(String::length))
.distinct()
.reduce("", (total, word) -> total + word + ", ").toLowerCase();
}

public static List<Integer> doubleNumbers(List<Integer> numbers) {
Expand All @@ -39,6 +41,9 @@ public static long sumAll(List<Integer> numbers) {
}

public static long sumOverThreeAndDouble(List<Integer> numbers) {
return 0;
return numbers.stream()
.filter(number -> number > 3)
.map(number -> number * 2)
.reduce(0, (total, number) -> total + number);
}
}
12 changes: 6 additions & 6 deletions src/main/java/nextstep/optional/Expression.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package nextstep.optional;

import java.util.Arrays;

enum Expression {
PLUS("+"), MINUS("-"), TIMES("*"), DIVIDE("/");

Expand All @@ -14,12 +16,10 @@ private static boolean matchExpression(Expression e, String expression) {
}

static Expression of(String expression) {
for (Expression v : values()) {
if (matchExpression(v, expression)) {
return v;
}
}

throw new IllegalArgumentException(String.format("%s는 사칙연산에 해당하지 않는 표현식입니다.", expression));
return Arrays.stream(values())
.filter(expressionData -> matchExpression(expressionData, expression))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException(String.format("%s는 사칙연산에 해당하지 않는 표현식입니다.", expression)));
}
}
9 changes: 8 additions & 1 deletion src/main/java/nextstep/optional/User.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package nextstep.optional;

import java.util.Optional;
import java.util.stream.Stream;

public class User {
private String name;
private Integer age;
Expand Down Expand Up @@ -33,7 +36,11 @@ public static boolean ageIsInRange1(User user) {
}

public static boolean ageIsInRange2(User user) {
return false;
return Optional.ofNullable(user)
.filter(userData -> userData.getAge() != null)
.filter(userData -> userData.getAge() >= 30 && userData.getAge() <= 45)
.map(userData -> true)
.orElse(false);
Comment on lines +42 to +43

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

힌트에서 제공된 부분 같지만
혹시 isPresent() 을 활용해주시는 건 어떠신가요?? 🤔🤔

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

좋은 것 같아요. 다음 미션 사다리 타기에서 수정해 놓도록 할게요~. 😄

}

@Override
Expand Down
11 changes: 5 additions & 6 deletions src/main/java/nextstep/optional/Users.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class Users {
static final User DEFAULT_USER = new User("codesquad", 100);
Expand All @@ -13,11 +14,9 @@ public class Users {
new User("honux", 45));

User getUser(String name) {
for (User user : users) {
if (user.matchName(name)) {
return user;
}
}
return DEFAULT_USER;
return users.stream()
.filter(user -> user.matchName(name))
.findFirst()
.orElse(DEFAULT_USER);
}
}
14 changes: 2 additions & 12 deletions src/test/java/nextstep/fp/CarTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,14 @@ public class CarTest {
@Test
public void 이동() {
Car car = new Car("pobi", 0);
Car actual = car.move(new MoveStrategy() {
@Override
public boolean isMovable() {
return true;
}
});
Car actual = car.move(() -> true);
assertThat(actual).isEqualTo(new Car("pobi", 1));
}

@Test
public void 정지() {
Car car = new Car("pobi", 0);
Car actual = car.move(new MoveStrategy() {
@Override
public boolean isMovable() {
return false;
}
});
Car actual = car.move(() -> false);
assertThat(actual).isEqualTo(new Car("pobi", 0));
}
}
6 changes: 3 additions & 3 deletions src/test/java/nextstep/fp/LambdaTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,19 +33,19 @@ public void runThread() throws Exception {

@Test
public void sumAll() throws Exception {
int sum = Lambda.sumAll(numbers);
int sum = Lambda.sumAllConditional(numbers, number -> true);
assertThat(sum).isEqualTo(21);
}

@Test
public void sumAllEven() throws Exception {
int sum = Lambda.sumAllEven(numbers);
int sum = Lambda.sumAllConditional(numbers, number -> number % 2 == 0);
assertThat(sum).isEqualTo(12);
}

@Test
public void sumAllOverThree() throws Exception {
int sum = Lambda.sumAllOverThree(numbers);
int sum = Lambda.sumAllConditional(numbers, number -> number > 3);
assertThat(sum).isEqualTo(15);
}
}