Issue
Hi I am trying to get user id
column and foreign_id
column from multiple csv files. After it loops (if (userAId.equals(userBId))
) it doesn't find the match of id ... I have tried the below code before and no luck. Any good suggestions?
public List<User> getObjectFiles(List<Map<String, String>>> csvFiles) {
List<User> user = new ArrayList<>();
List<Map<String, String>> userARows = csvFiles.get("userARows");
List<Map<String, String>> userBRows = csvFiles.get("userBRows");
List<String> userAId = new ArrayList<>();
for (Map<String, String> userARow: userARows) {
userAId = userARow.entry.stream()
.filter(key->key.getKey().equals("id")
.map(Map.Entry::getValue)
.collect(Collectors.toList());
}
List<String> userBId = new ArrayList<>();
for (Map<String, String> userBRow: userBRows) {
userBId = userBRow.entry.stream()
.filter(key->key.getKey().equals("foreign_id")
.map(Map.Entry::getValue)
.collect(Collectors.toList());
}
if (userAId.equals(userBId)) {
//....more code to add for List<User> user
}
return user;
}
Solution
Basically its not clear what you're asking here.
Reviewing the attached code:
The content of the loop, where you stream over map is strange:
You iterate over all the entries of the map instead of using a simple "get" and in addition you always rewrite the value instead of accumulating it.
Why not just:
List<String> userAId = new ArrayList<>();
for (Map<String, String> userARow: userARows) {
String userId = userARow.get("id");
userAIDs.add(userId);
}
This in turn could be rewritten as a stream:
List<String> userAIds = userARows
.stream()
.map(row -> row.get("id"))
.collect(Collectors.asList());
The code for User B looks exactly the same, actually you could even extract that into a private method to avoid the same code duplication, but its subjective:
private List<String> calculateByFieldName(List<Map<String, String>> content, String fieldName) {
return content.stream()
.map(row -> row.get(fieldName))
.collect(Collectors.asList());
}
// Then your code becomes:
public List<User> getObjectFiles(List<Map<String, String>>> csvFiles) {
List<User> user = new ArrayList<>();
List<Map<String, String>> userARows = csvFiles.get("userARows");
List<Map<String, String>> userBRows = csvFiles.get("userBRows");
List<String> userAId = calculateByFieldName(userARows, "id");
List<String> userBId = calculateByFieldName(userBRows, "foreign_id");
if (userAId.equals(userBId)) {
//....more code to add for List<User> user
}
return user;
}
Anyways, its not clear what do you mean by "the search stops" - obviously if the lists are not equals (have the same content and order of elements) the program won't enter the "if" condition and you'll get to the last line.
Answered By - Mark Bramnik
Answer Checked By - Senaida (JavaFixing Volunteer)