Reputation: 13
The task is to read the given file and return list of full names. I've separated the lines successfully and should be able to get both first and last names, but I'm a bit confused about how should I do that.
How am I able to get full names from readData()
?
What I'm looking for is this output ["Alice Smith", "Bob Brown", "Carol White", "David Doe"]
and not duplicated names.
My code looks like this so far:
public class GradeRepository {
public GradeRepository(){
readData();
}
public void readData() {
for (String line : readLines()) {
String[] parts = line.split("\\|");
String firstName = parts[0];
String lastName = parts[1];
String subject = parts[2];
String grade = parts[3];
System.out.println(firstName);
System.out.println(lastName);
System.out.println(subject);
System.out.println(grade);
System.out.println(Arrays.toString(parts));
}
}
public List<String> getFullNames() {
List<String> fullNames = new ArrayList<>();
return fullNames;
}
private List<String> readLines() {
try {
return Files.readAllLines(Paths.get("src/ex1/grades.txt"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Given text file: grades.txt
Alice|Smith|math|5
Bob|Brown|english|4
David|Doe|math|3
Bob|Brown|math|4
Bob|Brown|chemistry|5
Alice|Smith|english|4
Carol|White|chemistry|3
David|Doe|chemistry|4
Upvotes: 0
Views: 916
Reputation: 19575
readData
needs to be modified either to return a list of String[]
where each string array represents a line or a field List<String[]> data
needs to be created in GradeRepository
and populated in readData
.
Next, to get rid of duplicate names a Set<String>
should be used as suggested in the comments, and LinkedHashSet
implementation allows to keep the insertion order.
Example implementation where readData
returns a list:
public List<String[]> readData() {
List<String[]> data = new ArrayList<>();
for (String line : readLines()) {
String[] parts = line.split("\\|");
// ... print parts as above if necessary...
data.add(parts);
}
return data;
}
public Set<String> getFullNames() {
Set<String> fullNames = new LinkedHashSet<>();
for (String[] row : readData()) {
fullNames.add(row[0] + " " + row[1]);
}
return fullNames;
}
It may be more preferable to use Stream API to avoid creation of intermediate collections, so all these methods may be rewritten into one:
public Set<String> getFullNames() throws Exception {
return Files.lines(Path.of("dataset.txt")) // Stream<String>
.map(line -> line.split("\\|")) // Stream<String[]>
.filter(arr -> arr.length > 1) // ensure there are 2 columns at least
.map(arr -> arr[0] + " " + arr[1]) // Stream<String>
.collect(Collectors.toCollection(LinkedHashSet::new)); // get collection of unique names
}
Upvotes: 0