Monday 15 August 2011

java - Combining ArrayList without duplicates -



java - Combining ArrayList without duplicates -

import java.util.arraylist; import java.util.collections; public class smartcombining { public static void main(string[] args) { arraylist<integer> list1 = new arraylist<integer>(); arraylist<integer> list2 = new arraylist<integer>(); collections.addall(list1, 4, 3); collections.addall(list2, 5, 10, 4, 3, 7); smartcombine(list1, list2); system.out.println(list1); system.out.println(list2); } public static void smartcombine(arraylist<integer> first, arraylist<integer> second) { first.addall(second); } }

so, want combine 2 lists one, if sec list contains number first won't added. far method adds them together.

well, 1 way iterate through sec list while checking if each element exists in first list. if doesn't, add together it.

public static void smartcombine(arraylist<integer> first, arraylist<integer> second) { for(integer num : second) { // iterate through sec list if(!first.contains(num)) { // if first list doesn't contain current element first.add(num); // add together first list } } }

another way hold values within set (like hashset) doesn't allow duplicates. can combine them like:

first.addall(second);

one more way first remove elements first list exist in sec list (the ones duplicated). add together elements of sec list first list.

public static void smartcombine(arraylist<integer> first, arraylist<integer> second) { first.removeall(second); // remove elements duplicated first.addall(second); // add together elements sec list }

java arraylist

No comments:

Post a Comment