refactoring : loops - replace loop with pipeline

This commit is contained in:
haerong22
2022-04-03 16:48:18 +09:00
parent a78e242e4b
commit ceba83fab1
3 changed files with 73 additions and 0 deletions

View File

@@ -0,0 +1,25 @@
package com.example.refactoring._13_loops._33_replace_loop_with_pipeline;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Author {
private String company;
private String twitterHandle;
public Author(String company, String twitterHandle) {
this.company = company;
this.twitterHandle = twitterHandle;
}
static public List<String> TwitterHandles(List<Author> authors, String company) {
return authors.stream()
.filter(author -> author.company.equals(company) && Objects.nonNull(author.twitterHandle))
.map(author -> author.twitterHandle)
.toList();
}
}

View File

@@ -0,0 +1,29 @@
package com.example.refactoring._13_loops._33_replace_loop_with_pipeline._before;
import java.util.ArrayList;
import java.util.List;
public class Author {
private String company;
private String twitterHandle;
public Author(String company, String twitterHandle) {
this.company = company;
this.twitterHandle = twitterHandle;
}
static public List<String> TwitterHandles(List<Author> authors, String company) {
var result = new ArrayList<String> ();
for (Author a : authors) {
if (a.company.equals(company)) {
var handle = a.twitterHandle;
if (handle != null)
result.add(handle);
}
}
return result;
}
}

View File

@@ -0,0 +1,19 @@
package com.example.refactoring._13_loops._33_replace_loop_with_pipeline;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
class AuthorTest {
@Test
void twitterHandler() {
Author kim = new Author("ms", null);
Author lee = new Author("naver", "lee");
assertEquals(List.of("lee"), Author.TwitterHandles(List.of(kim, lee), "naver"));
}
}