2013-02-20 84 views
0

我需要加入两个Collection<String>,获取n个随机元素并将它们从存储它们的原始集合中删除。加入两个集合并获得一个随机元素

要加入收藏我想过遍历它们,并存储在一个自定义地图结构的方式:

  1. 具有存储在同一个密钥n次来
  2. 得到原来的集合。

有没有简单的方法来做到这一点?

你能帮我吗?

+0

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collection.html – NimChimpsky 2013-02-20 14:13:59

+1

您有重复的两个来源 - 那些原始列表中存在的以及在列表合并时创建的列表。你有什么要求处理这些? – Perception 2013-02-20 14:33:13

+0

地图(或第三个集合)只是提取n个随机项目的临时结构。问题是我想从原始集合中删除选定的元素。我不知道那么热... – ricknroll88 2013-02-20 14:37:55

回答

0

有趣的是你想​​使用该地图。我会建议使用MultiMap(例如Google's Guava)。它允许您保存一个密钥,然后保存一个值,全部属于该密钥。所以,你将只有两个键(对应你的原始Collections)。

另一种解决方案是将所有Collections添加到第三个Collection(有一个addAll(Collection c)方法可用)。假设没有重复的值,您可以检查第三个集合中的某个项目在迭代时是否是其他任何两个项目的一部分。

这些都是一种基本的方法来实现你问的任何问题,但值得一试。

希望这些指针有点帮助!

0

以下是否适合您?

import java.util.Collection; 
import java.util.HashSet; 
import java.util.List; 
import java.util.Random; 
import java.util.Set; 

import com.google.common.collect.Iterables; 
import com.google.common.collect.Lists; 
import com.google.common.collect.Sets; 

public class Combiner { 
    private static final Random rnd = new Random(); 

    public static void main(String[] args) { 
     Collection<String> boys = Sets.newHashSet("James", "John", "andrew", 
       "peter"); 
     Collection<String> girls = Sets.newHashSet("mary", "jane", "rose", 
       "danny"); 

     // Combine the two 
     Iterable<String> humans = Iterables.concat(boys, girls); 

     // Get n Random elements from the mix 
     int n = 2; 
     Collection<String> removed = randomSample4(humans, n); 

     // Remove from the original Collections 
     Iterables.removeAll(boys, removed); 
     Iterables.removeAll(girls, removed); 

     // or even 
     boys.removeAll(removed); 
     girls.removeAll(removed); 

     // And now we check if all is well 
     System.out.println(boys); 
     System.out.println(girls); 

    } 

    public static <T> Collection<T> randomSample4(Iterable<T> humans, int m) { 
     List<T> sample = Lists.newArrayList(humans); 
     Set<T> res = new HashSet<T>(m); 
     int n = sample.size(); 
     for (int i = n - m; i < n; i++) { 
      int pos = rnd.nextInt(i + 1); 
      T item = sample.get(pos); 
      if (res.contains(item)) 
       res.add(sample.get(i)); 
      else 
       res.add(item); 
     } 
     return res; 
    } 
} 

randomSample4方法已从this blog复制。

1

如何:

Collection<String> collection1 = new ArrayList<String>(); 
Collection<String> collection2 = new ArrayList<String>(); 

List<String> allElements = new ArrayList<String>(collection1); 
allElements.addAll(collection2); 
Collections.shuffle(allElements); 

Random random = new Random(); 
int n = 10; 
List<String> randomResults = new ArrayList<String>(n); 
for (int i = 0; i < n && !allElements.isEmpty(); i++) { 
    String randomElement = allElements.remove(random.nextInt(allElements.size())); 
    randomResults.add(randomElement); 
} 

collection1.removeAll(randomResults); 
collection2.removeAll(randomResults);