需要方法只返回Java中匹配的数字

时间:2013-09-19 02:40:26

标签: java set duplicates

/**
 * 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;
}

截至目前,它只返回所有userNumbers。我假设remove()方法将删除返回的任何重复值。我需要这个通过我的单元测试。

3 个答案:

答案 0 :(得分:2)

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)

答案 1 :(得分:1)

值得庆幸的是,Java为此提供了一种完全称为retainAll()的方法。为避免破坏任何一个原始集,请执行以下操作:

Set<String> intersection = new HashSet<String>(lotteryNumbers);
intersection.retainAll(userNumbers);
return intersection;

答案 2 :(得分:1)

您也可以使用Apache Commons - Collections进行与此类似的操作。具体来说,您可以使用CollectionUtils.intersection()

CollectionUtils.intersection(Arrays.asList(4,6,23,34,44,45),Arrays.asList(4,18,22,24,35,45)) // returns collection with 4,45

泛型版本位于http://sourceforge.net/projects/collections/