gpt4 book ai didi

java - Java 中需要方法仅返回匹配的数字

转载 作者:行者123 更新时间:2023-12-01 18:43:37 24 4
gpt4 key购买 nike

/**
* This method should compare two Sets of Integers and return a new
* Set of Integers that represent all of the matching numbers.
*
* For example, if the lotteryNumbers are (4, 6, 23, 34, 44, 45) and
* the userNumbers are (4, 18, 22, 24, 35, 45) then the returned Set
* of Integers should be (4, 45)
*
* @param lotteryNumbers the lottery numbers that were randomly generated.
* @param userNumbers the user picked numbers that were picked in the console.
* @return Set of matched numbers
*/
public Set<Integer> playLottery (Set<Integer> lotteryNumbers, Set<Integer> userNumbers) {
Set<Integer> listOfRandom = new HashSet<Integer>(lotteryNumbers);
listOfRandom.equals(lotteryNumbers);
listOfRandom.addAll(lotteryNumbers);

Set<Integer> s = new HashSet<Integer>(userNumbers);
s.equals(userNumbers);
s.addAll(userNumbers);

Set<Integer> e = new HashSet<Integer>();

for (Integer integer : userNumbers) {
if (userNumbers.equals(lotteryNumbers));
userNumbers.remove(lotteryNumbers);
}
return userNumbers;
}

到目前为止,它仅返回所有用户编号。我假设 remove() 方法会删除返回的任何重复值。我需要这个来通过我的单元测试。

最佳答案

retainAll()这就是您正在寻找的。

Set<Integer> lotteryNumbers = new TreeSet<Integer>();
// ... Populate it with 4, 6, 23, 34, 44, 45
Set<Integer> userNumbers = new TreeSet<Integer>();
// ... Populate it with 4, 18, 22, 24, 35, 45
userNumbers.retainAll(lotteryNumbers);
// userNumbers is now just (4, 45)

关于java - Java 中需要方法仅返回匹配的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18885433/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com