两个list做比较,取出第一个相等的数据及数据在两个list中的下标

public static void main(String args[]) {
		List list1 = new ArrayList();
		for (int i = 0; i < 900; i++) {
			list1.add(String.valueOf(i));
		}
		List list2 = new ArrayList<>();
		for (int i = 500; i < 1100; i++) {
			list2.add(String.valueOf(i));
		}

		System.out.println("list1:" + list1);
		System.out.println("list2:" + list2);
		getTheSameSection(list1, list2);
		getTheSameSection2(list1, list2);

	}

	public static String getTheSameSection(List list1, List list2) {
		long start = System.nanoTime();
		if(list1 == null &list1.size() == 0) {
			return "Parameter 1 is null or has length 0";
		}
		
		if(list2 == null &list2.size() == 0) {
			return "Parameter 2 is null or has length 0";
		}
		for (String item : list1) {// 遍历list2
			if (list2.contains(item)) {// 如果存在这个数
				System.out.println(item);
				System.out.println("list1Index:" + list1.indexOf(item));
				System.out.println("list2Index:" + list2.indexOf(item));
				long end = System.nanoTime();
				System.out.println("getTheSameSection spend "+ ( end-start ) + "ns");
				break;
			}
		}
		return null;
	}
	
	/*增加方法list2元素添加到map中,从map匹配list1数据的过程*/
	public static String getTheSameSection2(List list1, List list2) {
		long start = System.nanoTime();
		if(list1 == null &list1.size() == 0) {
			return "Parameter 1 is null or has length 0";
		}
		
		if(list2 == null &list2.size() == 0) {
			return "Parameter 2 is null or has length 0";
		}
		
		Map map = new HashMap<>();
		int count = 0;
		for(String s : list2) {
			
			if(map.containsKey(s)) {
				count++;
				continue;
			}else {
				map.put(s,count);
				count++;
			}
		}
		
		for(String s : list1) {
			if(map.containsKey(s)) {
				System.out.println("key:" + s +";Index:" +map.get(s));
				long end = System.nanoTime();
				System.out.println("getTheSameSection2 spend "+ (end-start) + "ns");
				return "key:" + s +";value:" +map.get(s);
			}
		}
		return null;
	}

当然这不是最快的方法,若有其他的思想,请各位观看者提出

 

你可能感兴趣的:(java算法)