ITeye博客

两个集合求交集

抛出异常的爱 · 2010-03-30 23:50 · 非技术 · Markdown

package aasdfsa;

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

import org.apache.commons.collections.Bag;
import org.apache.commons.collections.bag.HashBag;

public class TwoArrayList {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		TwoArrayList t = new TwoArrayList();
		
		List<String> one = new ArrayList<String>();
		List<String> two = new ArrayList<String>();
		long now = System.currentTimeMillis();
		int bigtime = 1000;//运行时间
		Random r = new Random();
		int key = 100000;//取值范围
		for(;;){
			int rr = r.nextInt(key);
			one.add(""+rr);
			rr = r.nextInt(1000);
			if(r.nextBoolean())two.add(""+rr);
		
			if(now+bigtime < System.currentTimeMillis()){
				break;
			}
		}
		System.out.println("first:"+one.size());
		System.out.println("next:"+two.size());
		System.out.println("union:"+t.union(one,two).size());

	}
	public List<String> union(List<String> one ,List<String> two){
		Bag bag1 = new HashBag(one);
		Bag bag2 = new HashBag(two);
		Set<String> set = new HashSet<String>();
		List<String> result = new ArrayList<String>();		
		set.addAll(one);
		set.addAll(two);
		System.out.println("totle:"+set.size());
		for (String temp : set) {
			long first = bag1.getCount(temp);
			long secend = bag2.getCount(temp);
			for(int i = 0 ; i < Math.min(first, secend);i++){
				result.add(temp);
			}			
		}
		return result;
	}

}

评论(3)

  1. #3 楼 · <>++< · 2011-10-18 13:05
    
    		public static List<String> listA = new ArrayList<String>(Arrays.asList("a",
    				"b", "c", "c", "d"));
    		public static List<String> listB = new ArrayList<String>(Arrays.asList("d",
    				"b", "c", "c", "d"));
    		
    		listA = new ArrayList<String>(new HashSet<String>(listA));
    		listA.retainAll(listB);
    
    		for (String str : listA) {
    			System.out.println(str);
    		}
    
    
    
    

    LZ 是这意思么?

  2. #2 楼 · 抛出异常的爱 · 2010-04-06 17:00

    我费心写这个是由于list中可能会有重复记录 重复次数可能很多。。。。

  3. #1 楼 · chenyulong1 · 2010-04-06 12:53

    不知博主是否己找到心怡的工作,看到这个帖子。写了两个方法。

    public static List<String> union(List<String> one, List<String> two) {
    		Set<String> t1 = new TreeSet<String>();
    		t1.addAll(one);
    		Set<String> t2 = new TreeSet<String>();
    		t2.addAll(two);
    		List<String> result = new ArrayList<String>();
    		for (String s : t1.size() < t2.size() ? t1 : t2) {
    			if (t1.size() < t2.size() ? t2.contains(s) : t1.contains(s)) {
    				result.add(s);
    			}
    		}
    		return result;
    		
    	}
    
    	public static List<String> union(List<List<String>> list) {
    		List<String> result = list.get(0);
    		if (list.size() == 0)
    			return result;
    		for (int i = 1; i < list.size(); i++) {
    			result = union(result, list.get(i));
    		}
    		return result;
    	}
    

评论功能维护中,当前仅展示历史评论。