Skip to content
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

f-hw-jv-stream-github-practice #1208

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
31 changes: 29 additions & 2 deletions src/main/java/practice/CandidateValidator.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,32 @@
package practice;

public class CandidateValidator {
//write your code here
import java.util.function.Predicate;
import model.Candidate;

public class CandidateValidator implements Predicate<Candidate> {
private static final int FIRST_INDEX_START = 0;
private static final int LAST_INDEX_END = 1;
private static final int MIN_AGE_FOR_CANDIDATE = 35;
private static final int MIN_PERIOD_IN_UKRAINE = 10;
private static final String NATIONALITY_FOR_CANDIDATE = "Ukrainian";

@Override
public boolean test(Candidate candidate) {
return candidate.getAge() >= MIN_AGE_FOR_CANDIDATE
&& candidate.isAllowedToVote()
&& candidate.getNationality().equals(NATIONALITY_FOR_CANDIDATE)
&& getLivePeriodInUkraine(candidate.getPeriodsInUkr()) >= MIN_PERIOD_IN_UKRAINE;
}

public static int getLivePeriodInUkraine(String periodsInUkr) {

Choose a reason for hiding this comment

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

The method getLivePeriodInUkraine assumes that the input string periodsInUkr is always in the correct format (e.g., '2000-2010'). If the format is incorrect or if there are parsing issues, this could throw a NumberFormatException or ArrayIndexOutOfBoundsException. Consider adding validation or exception handling to manage such cases.

Copy link
Contributor

Choose a reason for hiding this comment

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

Why public static?

Suggested change
public static int getLivePeriodInUkraine(String periodsInUkr) {
private int getLivePeriodInUkraine(String periodsInUkr) {

String[] split = periodsInUkr.split("-");
Copy link
Contributor

Choose a reason for hiding this comment

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

it also can be a constant

int period = 0;
try {
period = Integer.parseInt(split[LAST_INDEX_END])
- Integer.parseInt(split[FIRST_INDEX_START]);

Choose a reason for hiding this comment

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

The method getLivePeriodInUkraine assumes the input string is always in the correct format (e.g., 'YYYY-YYYY'). Consider adding validation to ensure the input format is correct before parsing, to prevent potential exceptions or incorrect calculations.

} catch (NumberFormatException e) {
System.out.println("String does not contain a parsable integer");

Choose a reason for hiding this comment

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

The current exception handling only prints an error message. Consider handling the exception more robustly, such as by returning a default value or rethrowing the exception with a custom message.

Copy link
Contributor

Choose a reason for hiding this comment

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

Let’s throw a runtime exception. Remove printing to the console. We'll explore logging a little later.

}
return period;
}
}
53 changes: 45 additions & 8 deletions src/main/java/practice/StreamPractice.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
package practice;

import java.util.Collections;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import model.Candidate;
import model.Cat;
import model.Person;

public class StreamPractice {
private final CandidateValidator candidateValidator = new CandidateValidator();

/**
* Given list of strings where each element contains 1+ numbers:
* input = {"5,30,100", "0,22,7", ...}
Expand All @@ -14,7 +21,13 @@ public class StreamPractice {
* "Can't get min value from list: < Here is our input 'numbers' >"
*/
public int findMinEvenNumber(List<String> numbers) {
return 0;
return numbers.stream()
.flatMap(s -> Arrays.stream(s.split(",")))
.mapToInt(Integer::parseInt)
.filter(n -> n % 2 == 0)
.min()
.orElseThrow(() -> new RuntimeException(
"Can't get min value from list:" + numbers));
}

/**
Expand All @@ -23,7 +36,11 @@ public int findMinEvenNumber(List<String> numbers) {
* But before that subtract 1 from each element on an odd position (having the odd index).
*/
public Double getOddNumsAverage(List<Integer> numbers) {
return 0D;
return IntStream.range(0, numbers.size())
.map(index -> index % 2 != 0 ? numbers.get(index) - 1 : numbers.get(index))
.filter(n -> n % 2 != 0)
.average()
.orElseThrow(NoSuchElementException::new);
Copy link
Contributor

Choose a reason for hiding this comment

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

Let’s add a message

}

/**
Expand All @@ -35,7 +52,10 @@ public Double getOddNumsAverage(List<Integer> numbers) {
* Example: select men who can be recruited to army (from 18 to 27 years old inclusively).
*/
public List<Person> selectMenByAge(List<Person> peopleList, int fromAge, int toAge) {
return Collections.emptyList();
return peopleList.stream()
.filter(p -> p.getSex().equals(Person.Sex.MAN)
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
.filter(p -> p.getSex().equals(Person.Sex.MAN)
.filter(p -> p.getSex() == Person.Sex.MAN

the same

&& p.getAge() >= fromAge && p.getAge() <= toAge)
.collect(Collectors.toList());
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
.collect(Collectors.toList());
.toList();

}

/**
Expand All @@ -50,7 +70,14 @@ public List<Person> selectMenByAge(List<Person> peopleList, int fromAge, int toA
*/
public List<Person> getWorkablePeople(int fromAge, int femaleToAge,
int maleToAge, List<Person> peopleList) {
return Collections.emptyList();
return peopleList.stream()
.filter(person -> ((person.getSex().equals(Person.Sex.MAN)
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
.filter(person -> ((person.getSex().equals(Person.Sex.MAN)
.filter(person -> ((person.getSex() == Person.Sex.MAN

Let’s compare enums in this way

&& person.getAge() > fromAge
&& person.getAge() <= maleToAge)

Choose a reason for hiding this comment

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

In the getWorkablePeople method, the condition person.getAge() > fromAge should be person.getAge() >= fromAge to include the lower bound age for men, as specified in the task description.

|| (person.getSex().equals(Person.Sex.WOMAN)
&& person.getAge() >= fromAge
&& person.getAge() <= femaleToAge)))
Copy link
Contributor

Choose a reason for hiding this comment

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

for complicated conditional, it is better to use Predicate

Copy link
Author

Choose a reason for hiding this comment

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

how I can do this? if fromAge, femaleToAge and maleToAge is a variable that we accept as input to the method. They are not constant.

.collect(Collectors.toList());
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
.collect(Collectors.toList());
.toList();

fix it everywhere

}

/**
Expand All @@ -59,7 +86,13 @@ public List<Person> getWorkablePeople(int fromAge, int femaleToAge,
* return the names of all cats whose owners are women from `femaleAge` years old inclusively.
*/
public List<String> getCatsNames(List<Person> peopleList, int femaleAge) {
return Collections.emptyList();
return peopleList.stream()
.filter(person -> person.getSex().equals(Person.Sex.WOMAN)
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
.filter(person -> person.getSex().equals(Person.Sex.WOMAN)
.filter(person -> person.getSex() == Person.Sex.WOMAN

the same

&& person.getAge() >= femaleAge)
.map(Person::getCats)
.flatMap(Collection::stream)
.map(Cat::getName)
.collect(Collectors.toList());
}

/**
Expand All @@ -69,12 +102,16 @@ public List<String> getCatsNames(List<Person> peopleList, int femaleAge) {
* names sorted alphabetically.
* The requirements are: person should be older than 35 years, should be allowed to vote,
* have nationality - 'Ukrainian'
* and live in Ukraine for 10 years. For the last requirement use field periodsInUkr,
* and live in Ukraine for 10 years. For the last requirement use field Ukrainian',

Choose a reason for hiding this comment

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

The comment seems to have a typo: 'Ukrainian' is mentioned twice. Ensure the comment accurately reflects the field name used in the Candidate class.

Copy link
Contributor

Choose a reason for hiding this comment

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

revert task description

* which has following view: "2002-2015"
* We want to reuse our validation in future, so let's write our own impl of Predicate
* parametrized with Candidate in CandidateValidator.
*/
public List<String> validateCandidates(List<Candidate> candidates) {
return Collections.emptyList();
return candidates.stream()
.filter(candidateValidator)
.map(Candidate::getName)
.sorted()
.toList();
}
}
Loading