Last active
July 19, 2023 01:57
-
-
Save diegolirio/f2d05bf51cc9f3faf85fd6e1a4678cd0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package demointerviews.collection; | |
import java.util.*; | |
/** | |
* You must improve the processing time of the "solution" method | |
*/ | |
public class ChallengeForInsideFor { | |
public static final long NUMBERS_OF_ITEMS = 100000; | |
public static void main(String[] args) { | |
ChallengeForInsideFor self = new ChallengeForInsideFor(); | |
List<Customer> customersName = self.getCustomersName(); | |
List<Customer> customersAge = self.getCustomersAge(); | |
var start = System.currentTimeMillis(); | |
List<Customer> solution = new Solution().solution(customersName, customersAge); | |
System.out.println("Time of solution method -> " + (System.currentTimeMillis() - start)); | |
if(solution.stream().anyMatch(it -> "ERROR".equals(it.ref()))) { | |
throw new RuntimeException("ERROR, elements didn't match"); | |
} | |
} | |
private List<Customer> getCustomersName() { | |
var list = new ArrayList<Customer>(); | |
for (int i = 1; i <= NUMBERS_OF_ITEMS; i++) { | |
list.add( | |
new Customer( | |
(long) i, UUID.randomUUID().toString().substring(0, 4), null, i+"" | |
) | |
); | |
} | |
return list; | |
} | |
private List<Customer> getCustomersAge() { | |
var list = new ArrayList<Customer>(); | |
for (int i = 1; i <= NUMBERS_OF_ITEMS; i++) { | |
list.add( | |
new Customer( | |
(long) i, null, new Random().nextInt(18, 82), i+"" | |
) | |
); | |
} | |
return list; | |
} | |
} | |
record Customer(Long id, String name, Integer age, String ref) {} | |
class Solution { | |
public List<Customer> solution(List<Customer> listName, List<Customer> listAge) { | |
// TODO ==> You must fix only this method, keep solution method signatue | |
List<Customer> customersComplete = new ArrayList<Customer>(); | |
for(var cName : listName) { | |
for (var cAge : listAge) { | |
if(Objects.equals(cName.id(), cAge.id())) { | |
customersComplete.add( | |
new Customer( | |
cName.id(), | |
cName.name(), | |
cAge.age(), | |
cName.ref().equals(cAge.ref()) ? cName.ref() : "ERROR" | |
) | |
); | |
} | |
} | |
} | |
return customersComplete; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment