I have 2 Strings:
A1=[Rettangolo, Quadrilatero, Rombo, Quadrato]
A2=[Rettangolo, Rettangolo, Rombo, Quadrato]
I want to obtain this: "I have found "Quadrilatero", instead of "Rettangolo" ".
If I use removeAll() or retainAll() it doesn't work because I have 2 instances of "Rettangolo".
In fact, if I use a1.containsAll(a2), I get true and I want false.
Thanks all for considering my request.
Use the remove method from ArrayList. It only removes the first occurance.
public static void main(String []args){
//Create ArrayLists
String[] A1 = {"Rettangolo", "Quadrilatero", "Rombo", "Quadrato"};
ArrayList<String> a1=new ArrayList(Arrays.asList(A1));
String[] A2 ={"Rettangolo", "Rettangolo", "Rombo", "Quadrato"};
ArrayList<String> a2=new ArrayList(Arrays.asList(A2));
// Check ArrayLists
System.out.println("a1 = " + a1);
System.out.println("a2 = " + a2);
// Find difference
for( String s : a1)
a2.remove(s);
// Check difference
System.out.println("a1 = " + a1);
System.out.println("a2 = " + a2);
}
Result
a1 = [Rettangolo, Quadrilatero, Rombo, Quadrato]
a2 = [Rettangolo, Rettangolo, Rombo, Quadrato]
a1 = [Rettangolo, Quadrilatero, Rombo, Quadrato]
a2 = [Rettangolo]
These two classes might help. Let me know how I can improve this further.
Feel free to use the code below in your own work.
I must point out that the current code does not take care of repeated list elements.
import java.util.List;
public class ListDiff<T> {
private List<T> removed;
private List<T> added;
public ListDiff(List<T> removed, List<T> added) {
super();
this.removed = removed;
this.added = added;
}
public ListDiff() {
super();
}
public List<T> getRemoved() {
return removed;
}
public List<T> getAdded() {
return added;
}
}
Util class.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class ListUtil {
public static <T> ListDiff<T> diff(List<T> one, List<T> two) {
List<T> removed = new ArrayList<T>();
List<T> added = new ArrayList<T>();
for (int i = 0; i < one.size(); i++) {
T elementOne = one.get(i);
if (!two.contains(elementOne)) {
//element in one is removed from two
removed.add(elementOne);
}
}
for (int i = 0; i < two.size(); i++) {
T elementTwo = two.get(i);
if (!one.contains(elementTwo)) {
//element in two is added.
added.add(elementTwo);
}
}
return new ListDiff<T>(removed, added);
}
public static <T> ListDiff<T> diff(List<T> one, List<T> two, Comparator<T> comparator) {
List<T> removed = new ArrayList<T>();
List<T> added = new ArrayList<T>();
for (int i = 0; i < one.size(); i++) {
T elementOne = one.get(i);
boolean found = false;
//loop checks if element in one is found in two.
for (int j = 0; j < two.size(); j++) {
T elementTwo = two.get(j);
if (comparator.compare(elementOne, elementTwo) == 0) {
found = true;
break;
}
}
if (found == false) {
//element is not found in list two. it is removed.
removed.add(elementOne);
}
}
for (int i = 0; i < two.size(); i++) {
T elementTwo = two.get(i);
boolean found = false;
//loop checks if element in two is found in one.
for (int j = 0; j < one.size(); j++) {
T elementOne = one.get(j);
if (comparator.compare(elementTwo, elementOne) == 0) {
found = true;
break;
}
}
if (found == false) {
//it means element has been added to list two.
added.add(elementTwo);
}
}
return new ListDiff<T>(removed, added);
}
public static void main(String args[]) {
String[] arr1 = { "london", "newyork", "delhi", "singapore", "tokyo", "amsterdam" };
String[] arr2 = { "london", "newyork", "delhi", "singapore", "seoul", "bangalore", "oslo" };
ListDiff<String> ld = ListUtil.diff(Arrays.asList(arr1), Arrays.asList(arr2));
System.out.println(ld.getRemoved());
System.out.println(ld.getAdded());
ld = ListUtil.diff(Arrays.asList(arr1), Arrays.asList(arr2), new Comparator<String>() {
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
}); //sample for using custom comparator
System.out.println(ld.getRemoved());
System.out.println(ld.getAdded());
}
}
Here are three solutions.
An implementation that uses a remove method.
public static boolean same(List<String> list1, List<String> list2){
if (list1.size() != list2.size())
return false;
List<String> temp = new ArrayList<String>(list1);
temp.removeAll(list2);
return temp.size() == 0;
}
A solution that sorts then compares.
public static boolean same(List<String> list1, List<String> list2){
if (list1.size() != list2.size())
return false;
Collections.sort(list1);
Collections.sort(list2);
for (int i=0;i<list1.size();i++){
if (!list1.get(i).equals(list2.get(i)))
return false;
}
return true;
}
And, just for fun, you could do this by doing a word count difference between the two arrays. It wouldn't be the most efficient, but it works and possibly could be useful.
public static boolean same(List<String> list1, List<String> list2){
Map<String,Integer> counts = new HashMap<String,Integer>();
for (String str : list1){
Integer i = counts.get(str);
if (i==null)
counts.put(str, 1);
else
counts.put(str, i+1);
}
for (String str : list2){
Integer i = counts.get(str);
if (i==null)
return false; /// found an element that's not in the other
else
counts.put(str, i-1);
}
for (Entry<String,Integer> entry : counts.entrySet()){
if (entry.getValue() != 0)
return false;
}
return true;
}
This will find the intersection between two arrays for this specific case you have explained.
String[] A1 = { "Rettangolo", "Quadrilatero", "Rombo", "Quadrato" };
String[] A2 = { "Rettangolo", "Rettangolo", "Rombo", "Quadrato" };
ArrayList<String> a1 = new ArrayList<String>(Arrays.asList(A1));
ArrayList<String> a2 = new ArrayList<String>(Arrays.asList(A2));
a1.removeAll(a2);
System.out.println("I have found " + a1);
I hope this will help you
String[] A1 = {"Rettangolo", "Quadrilatero", "Rombo", "Quadrato"};
String[] A2 ={"Rettangolo", "Rettangolo", "Rombo", "Quadrato"};
Set<String> set1 = new HashSet<String>();
Set<String> set2 = new HashSet<String>();
set1.addAll(Arrays.asList(A1));
set2.addAll(Arrays.asList(A2));
set1.removeAll(set2);
System.out.println(set1);// ==> [Quadrilatero]
Related
I've an ArrayList which contains pairs of integers( say int i, int j). But it may be contains duplicates pairs (like (int i, int j) and (int j, int i)). Now how can I remove duplicates from it in O(n) time complexity.
Updated code:
class Pair<t1,t2>
{
int i, j;
Pair(int i,int j){
this.i=i;
this.j=j;
}
}
public class My
{
public static void main(String[] args) {
Pair p;
List<Pair<Integer,Integer>> src = Arrays.asList(new Pair(1,2),
new Pair(2,3), new Pair(2,1),new Pair(1,2));
HashSet<String> dest = new HashSet();
for(int i=0; i < src.size(); i++) {
p=src.get(i);
if(dest.contains(p.j+" "+p.i)) {
System.out.println("duplicacy");
}
else {
dest.add(p.i+" "+p.j);
}
}
System.out.println("set is = "+dest);
List<Pair<Integer,Integer>> ans=new ArrayList();
String temp;
int i,j;
Iterator<String> it=dest.iterator();
while(it.hasNext())
{
temp=it.next();
i=Integer.parseInt(temp.substring(0,temp.indexOf(' ')));
j=Integer.parseInt(temp.substring(temp.indexOf('
')+1,temp.length()));
ans.add(new Pair(i,j));
}
for(Pair i_p:ans) {
System.out.println("Pair = "+i_p.i+" , "+i_p.j);
}
}//end of main method
}//end of class My
This code is working fine but I want to know it performance wise, I mean its overall time complexity ?
If you can modify Pair class, just implement equals() and hashCode():
public class Pair {
private int a;
private int b;
public Pair(int a, int b) {
this.a = a;
this.b = b;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
return (a == pair.a && b == pair.b) || (a == pair.b && b == pair.a);
}
#Override
public int hashCode() {
return Objects.hashCode(new HashSet<>(Arrays.asList(a,b)));
}
#Override
public String toString() {
return "Pair{" +
"a=" + a +
", b=" + b +
'}';
}
}
Then just create a new Set<Pair>:
List<Pair> pairs = Arrays.asList(new Pair(1, 2), new Pair(2, 1), new Pair(3, 2));
Set<Pair> pairSet = new HashSet<>(pairs);
System.out.println(pairSet);
Output:
[Pair{a=1, b=2}, Pair{a=3, b=2}]
If you can't modify Pair class:
List<Pair> pairs = Arrays.asList(new Pair(1, 2), new Pair(2, 1), new Pair(3, 2));
Set<Pair> pairSet = pairs.stream()
.map(pair -> new HashSet<>(Arrays.asList(pair.getA(), pair.getB())))
.distinct()
.map(integers -> {
Iterator<Integer> iterator = integers.stream().iterator();
return new Pair(iterator.next(), iterator.next());
})
.collect(Collectors.toSet());
System.out.println(pairSet);
Output:
[Pair{a=1, b=2}, Pair{a=2, b=3}]
If you want, you can convert your Set back to a list:
List<Pair> list = new ArrayList<>(set);
But it's most likely unnecessary.
Make only one loop throught list of Pairs and collect by the way in HashSet processed pair and it's reversed copy:
List<Pair<Integer,Integer>> lp = Arrays.asList(new Pair(1,2),
new Pair(2,3),
new Pair(1,2),
new Pair(2,1));
Set<Pair<Integer,Integer>> sp = new HashSet<>();
List<Pair<Integer,Integer>> ulp = lp.stream()
.collect(ArrayList::new,
(l,p)-> { Pair<Integer,Integer> p1 = new Pair(p.getValue(), p.getKey());
if (!(sp.contains(p))&&!(sp.contains(p1))){
l.add(p);
sp.add(p);
sp.add(p1);
}} , List::addAll);
System.out.println(ulp);
Since the contains() of HashSet runs in O(1) time (See this and other references) you can use the following method which is the overall O(n):
import java.util.*;
import javafx.util.*;
public class Main
{
public static void main(String[] args) {
List<Pair<Integer,Integer>> src = Arrays.asList(new Pair(1,2), new Pair(2,3), new Pair(2,1));
HashSet<Pair<Integer,Integer>> dest = new HashSet();
for(int i=0; i < src.size(); i++) {
if(dest.contains(src.get(i)) ||
dest.contains(new Pair(src.get(i).getValue(),src.get(i).getKey()))) {
}else {
dest.add(src.get(i));
}
}
System.out.println(dest);
}
}
EDIT 1:
You can use Map.Entry instead of javafx.util.pair. Do the program without Javafx is as follow.
import java.util.*;
public class Main
{
public static void main(String[] args) {
List<Map.Entry<Integer,Integer>> src = Arrays.asList(new AbstractMap.SimpleEntry(1,2),
new AbstractMap.SimpleEntry(2,3), new AbstractMap.SimpleEntry(2,1));
HashSet<Map.Entry<Integer,Integer>> dest = new HashSet();
for(int i=0; i < src.size(); i++) {
if(dest.contains(src.get(i)) ||
dest.contains(new AbstractMap.SimpleEntry(src.get(i).getValue(),src.get(i).getKey()))) {
}else {
dest.add(src.get(i));
}
}
System.out.println(dest);
}
}
ArrayList<String> a1=new ArrayList<String>();
a1.add("Item1");
a1.add("58584272");
a1.add("62930912");
ArrayList<String> a2=new ArrayList<String>();
a2.add("Item2");
a2.add("9425650");
a2.add("96088250");
ArrayList<String> a3=new ArrayList<String>();
a3.add("Item3");
a3.add("37469674");
a3.add("46363902");
ArrayList<String> a4=new ArrayList<String>();
a4.add("Item4");
a4.add("18666489");
a4.add("88046739");
List<List<String>> a5=new ArrayList<List<String>>();
a5.add(a1);
a5.add(a2);
a5.add(a3);
a5.add(a4);
TreeSet<List<String>> ts=new TreeSet<List<String>>(new mycomparator());
for(int i=0; i<=a.size()-1; i++){
ts.add(a5.get(i));
}
System.out.Println(ts); // Returns [[Item1, 58584272, 62930912]]
public class mycomparator implements Comparator{
static int order,paramenter=0;
#Override
public int compare(Object o1, Object o2) {
List<String> a1=(List<String>)o1;
List<String> a2=(List<String>)o1;
int b1=Integer.parseInt(a1.get(paramenter));
int b2=Integer.parseInt(a2.get(paramenter));
if(b1>b2){ return order==1?1:-1;}
else if (b1<b2){return order==1?-1:1;}
else{return 0;}
}
}
In the above code,I am trying to add objects to tree set,After adding all the elements when I try to print the treeset,only the first element get added.Why this is happening ?
Result --> [[Item1, 58584272, 62930912]]
Your code has so many problems:
Using raw Comparator instead of parametrized version.
Using wrong variable in the for loop.
Using static variables in the comparator.
On a side note, you should follow the Java naming conventions e.g. the class mycomparator should be named as MyComparator.
Given below is the code incorporating these comments:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
class MyComparator implements Comparator<List<String>> {
int order, paramenter;
MyComparator(int order, int paramenter) {
this.order = order;
this.paramenter = paramenter;
}
#Override
public int compare(List<String> o1, List<String> o2) {
int b1 = Integer.parseInt(o1.get(paramenter));
int b2 = Integer.parseInt(o2.get(paramenter));
if (b1 > b2) {
return order == 1 ? 1 : -1;
} else if (b1 < b2) {
return order == 1 ? -1 : 1;
} else {
return 0;
}
}
}
public class Main {
public static void main(String[] args) {
ArrayList<String> a1 = new ArrayList<String>();
a1.add("Item1");
a1.add("58584272");
a1.add("62930912");
ArrayList<String> a2 = new ArrayList<String>();
a2.add("Item2");
a2.add("9425650");
a2.add("96088250");
ArrayList<String> a3 = new ArrayList<String>();
a3.add("Item3");
a3.add("37469674");
a3.add("46363902");
ArrayList<String> a4 = new ArrayList<String>();
a4.add("Item4");
a4.add("18666489");
a4.add("88046739");
List<ArrayList<String>> a5 = new ArrayList<ArrayList<String>>();
a5.add(a1);
a5.add(a2);
a5.add(a3);
a5.add(a4);
TreeSet<List<String>> ts = new TreeSet<List<String>>(new MyComparator(0, 1));
for (int i = 0; i < a5.size(); i++) {
ts.add(a5.get(i));
}
System.out.println(ts);
}
}
Output:
[[Item1, 58584272, 62930912], [Item3, 37469674, 46363902], [Item4, 18666489, 88046739], [Item2, 9425650, 96088250]]
Note: I've just implemented your logic inside your compare method as it is. If you can tell me the exact requirement, I will update the code inside compare or you can update it yourself.
It is because of this code loop limit you use "i<=a.size()-1".
The "a" is never defined in your code, meaning size to be provided is zero, then you minus 1, so it will be less than zero.
That means this loop will only be triggered once.
for(int i=0; i<=a.size()-1; i++){
ts.add(a5.get(i));
}
You have implemented the comparator incorrectly. Check the following code:
List<String> a1 = new ArrayList<String>();
a1.add("Item1");
a1.add("58584272");
a1.add("62930912");
List<String> a2 = new ArrayList<String>();
a2.add("Item2");
a2.add("9425650");
a2.add("96088250");
List<String> a3 = new ArrayList<String>();
a3.add("Item3");
a3.add("37469674");
a3.add("46363902");
List<String> a4 = new ArrayList<String>();
a4.add("Item4");
a4.add("18666489");
a4.add("88046739");
List<List<String>> a = new ArrayList<List<String>>();
a.add(a1);
a.add(a2);
a.add(a3);
a.add(a4);
Comparator<List<String>> comparator = new Comparator<List<String>>() {
#Override
public int compare(List<String> a1, List<String> a2) {
String b1 = a1.get(0);
String b2 = a2.get(0);
return b1.compareTo(b2);
}
};
TreeSet<List<String>> ts = new TreeSet<List<String>>(comparator);
for (int i = 0; i <= a.size() - 1; i++) {
ts.add(a.get(i));
}
System.out.println(ts);
I need to group a given sort list by some given "blocks" or "groups" of elements. For example:
Given a list:
[A, B, C, D, E, F, G, H, I, J]
And groups
[A, C, D]
[F, E]
[J, H, I]
the result should be
[A, C, D, B, F, E, G, J, H, I]
The blocks of elements can not be mixed with non-group elements. The blocks should have the same order. The other elements of the list should mantain their order.
I have already found a solution. But it's not the most efficient code as you will see.
I'm using java 6 also...
public static List<CategoryProduct> sortProductsByBlocks(List<CategoryProduct> products, CategoryBlocks categoryBlocks) {
if (!validateCategoryBlocks(categoryBlocks)) {
return products;
}
Map<String, BlockView> mapProductByBlock = mapBlocksByPartnumber(categoryBlocks);
Map<String, BlockView> mapFirstProductByBlock = mapFirstProductByBlock(categoryBlocks);
Map<Integer, Block> blocksById = blocksById(categoryBlocks);
List<CategoryProduct> sortedProduct = Lists.newArrayList();
Map<String, CategoryProduct> productsMapByPartNumber = ProductHelper.getProductsMapByPartNumber(products);
List<CategoryProduct> processedProducts = Lists.newArrayList();
int j = 0;
for (int i = 0; i < products.size(); i++) {
CategoryProduct product = products.get(i);
if (blocksById.isEmpty() && !processedProducts.contains(product)) {
sortedProduct.add(j++, product);
processedProducts.add(product);
}
if (!processedProducts.contains(product) && (mapFirstProductByBlock.get(product.getPartNumber()) != null
|| mapProductByBlock.get(product.getPartNumber()) == null)) {
BlockView blockView = mapProductByBlock.get(product.getPartNumber());
if (blockView != null) {
Block block = blocksById.get(blockView.getBlockId());
if (block == null) {
sortedProduct.add(j++, product);
continue;
}
for (BlockProduct blockProduct : block.getProducts()) {
CategoryProduct categoryProduct = productsMapByPartNumber.get(blockProduct.getPartnumber());
sortedProduct.add(j++, categoryProduct);
processedProducts.add(categoryProduct);
}
blocksById.remove(blockView.getBlockId());
} else {
sortedProduct.add(j++, product);
processedProducts.add(product);
}
}
}
return sortedProduct;
}
Any advice to improve and make it faster will be welcome.
(edit with the improved code)
public static List<CategoryProduct> sortProductsByBlocks2(List<CategoryProduct> products,
CategoryBlocks categoryBlocks) {
if (!validateCategoryBlocks(categoryBlocks)) {
return products;
}
Map<String, Integer> blocksIdByFirstPartnumber = Maps.newHashMap();
List<String> partnumbersInBlocks = Lists.newArrayList();
for (int k = 0; k < categoryBlocks.getBlocks().size(); k++) {
Block block = categoryBlocks.getBlocks().get(k);
if (block != null && block.getProducts() != null) {
for (int i = 0; i < block.getProducts().size(); i++) {
BlockProduct blockProduct = block.getProducts().get(i);
if (i == 0) {
blocksIdByFirstPartnumber.put(blockProduct.getPartnumber(), k);
} else {
partnumbersInBlocks.add(blockProduct.getPartnumber());
}
}
}
}
CategoryProduct[] result = new CategoryProduct[products.size()];
Map<String, Integer> productsIndex = Maps.newHashMap();
Map<String, CategoryProduct> categoryProductByPartnumber = Maps.newHashMap();
int indexResult = 0;
for (CategoryProduct categoryProduct : products) {
String partNumber = categoryProduct.getPartNumber();
if (!partnumbersInBlocks.contains(partNumber)) {
if (blocksIdByFirstPartnumber.get(partNumber) != null) {
Block categoryProductBlock = categoryBlocks.getBlocks()
.get(blocksIdByFirstPartnumber.get(partNumber));
result[indexResult] = categoryProduct;
indexResult++;
for (int i = 1; i < categoryProductBlock.getProducts().size(); i++) {
BlockProduct blockProduct = categoryProductBlock.getProducts().get(i);
if (categoryProductByPartnumber.get(blockProduct.getPartnumber()) != null) {
result[indexResult] = categoryProductByPartnumber.get(blockProduct.getPartnumber());
} else {
productsIndex.put(blockProduct.getPartnumber(), indexResult);
result[indexResult] = null;
}
indexResult++;
}
} else {
result[indexResult] = categoryProduct;
indexResult++;
}
} else {
if (productsIndex.get(partNumber) != null) {
result[productsIndex.get(partNumber)] = categoryProduct;
} else {
categoryProductByPartnumber.put(partNumber, categoryProduct);
}
}
}
return Lists.newArrayList(Arrays.asList(result));
}
Performance:
Elements New algorithm Old algorithm
1200 0.002s 0.129s
12000 0.021s 14.673s
Form the code you submitted, I cannot figure out how your algorithm is fully working.
I can write another algorithm that will do the task.
Mark the first element for each group
[A,C,D] -> A
Remove from list(to_be_sorted) all elements from groups that are not marked
[A,C,D] -> remove [C,D]
perform sort on list
result ([A,B,F,G,J])
place removed element based on Mark
Initial Sorted List [A,B,F,G,J]
A->add [C,D]
List is [A,C,D,B,F,G,J]
B->as it is
F->add [E]
List is [A,C,D,B,F,E,G,J]
G->as it is
J->add [H,I]
Final Sorted List [A,C,D,B,F,E,G,J,H,I]
Time complexity is the same as sorting algorithm
By your definition it isn't entirely clear what the conditions are to merge the results from your given list and 'groups' ( arrays ). However, here is a solution based on your requirements using the assertion
"You want the first element of the list not contained in any of the groups inserted between the groups... "
public class MergeArrays {
private static final List<String> FIRST = new ArrayList<>(Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", "I", "J"));
private static final List<String> SECOND = new ArrayList<>(Arrays.asList("A", "C", "D"));
private static final List<String> THIRD = new ArrayList<>(Arrays.asList("F", "E"));
private static final List<String> FOURTH = new ArrayList<>(Arrays.asList("J", "H", "I"));
public static List<String> merge(List<String> source, List<String>... lists) {
List<String> result = new ArrayList<>();
for (List<String> list : lists) {
for (String value : list) {
source.remove(value);
}
}
for (List<String> list : lists) {
String value = null;
if (source.size() > 0) {
value = source.get(0);
source.remove(0);
}
result.addAll(merge(value, list));
}
return result;
}
public static List<String> merge(String value, List<String> list) {
List<String> result = new ArrayList<>(list);
if (value != null) {
result.add(value);
}
return result;
}
public static void main(String[] args) {
List<String> result = merge(FIRST, SECOND, THIRD, FOURTH);
System.out.println(result);
}
}
//Results
[A, C, D, B, F, E, G, J, H, I]
I have this class and in the printVotes method I had to do the if statement every time to print each votes. Is there any way to combine both the if statements. Could I print all the names of the candidates and the number of votes they got at the same time?
public class TestCandidate {
public static void main(String[] args)
{
Canidate[] canidate = new Canidate[5];
// create canidate
canidate[0] = new Canidate("John Smith", 5000);
canidate[1] = new Canidate("Mary Miller", 4000);
canidate[2] = new Canidate("Michael Duffy", 6000);
canidate[3] = new Canidate("Tim Robinson", 2500);
canidate[4] = new Canidate("Joe Ashtony", 1800);
printVotes(canidate) ;
}
public static void printVotes(Canidate [] List)
{
double max;
int index;
if (List.length != 0)
{
index = 0;
for (int i = 1; i < List.length; i++)
{
}
System.out.println(List[index]);
}
if (List.length != 0)
{
index = 1;
for (int i = 1; i < List.length; i++)
{
}
System.out.println(List[index]);
return;
}
}
}
If you pass in a List<Candidate> candidates; and assuming that each candidate has a List<Integer> Votes:
List<Integer> votes= new ArrayList<Integer>() ;
for(Candidate c:candidates)
{
votes.add(c.GetVote()) ;
}
for(Integer v:votes)
{
System.out.println(v);
}
You could override the Candidate class's toString() method like so:
public String toString() {
return "Candidate Name: " + this.name + "\nVotes: " + this.votes;
}
Then your printVotes method would look something like this:
public static void printVotes(Candidate[] list) {
for(Candidate c : list) {
System.out.println(c);
}
}
As someone else mentioned, avoid using capital letters in variable names especially in cases where words such as List are used. List is a collection type and can be easily confused.
This is a pice of my code :
ArrayList<String> Alist= new ArrayList<String>();
ArrayList<String> Blist= new ArrayList<String>();
Alist.add("gsm");
Alist.add("tablet");
Alist.add("pc");
Alist.add("mouse");
Blist.add("gsm");
Blist.add("something");
Blist.add("pc");
Blist.add("something");
so i have two array list i want to compare all items and check if they are not equal and if they are to print out only the items that are not equal.
so i make something like this:
http://postimage.org/image/adxix2i13/
sorry for the image but i have somekind of bug when i post here a for looop.
and the result is :
not equals..:tablet
not equals..:pc
not equals..:mouse
not equals..:gsm
not equals..:tablet
not equals..:pc
not equals..:mouse
not equals..:gsm
not equals..:tablet
not equals..:pc
not equals..:mouse
not equals..:gsm
not equals..:tablet
i want to print only the 2 that are not equal in the example they are gsm and pc
not equals..:gsm
not equals..:pc
Don't use != to compare strings. Use the equals method :
if (! Blist.get(i).equals(Alist.get(j))
But this wouldn't probably fix your algorithmic problem (which isn't clear at all).
If what you want is know what items are the same at the same position, you could use a simple loop :
int sizeOfTheShortestList = Math.min(Alist.size(), Blist.size());
for (int i=0; i<sizeOfTheShortestList; i++) {
if (Blist.get(i).equals(Alist.get(i))) {
System.out.println("Equals..: " + Blist.get(i));
}
}
If you want to get items that are in both lists, use
for (int i = 0; i < Alist.size(); i++) {
if (Blist.contains(Alist.get(i))) {
System.out.println("Equals..: " + Alist.get(i));
}
}
You can use the RemoveAll(Collection c) on one of the lists, if you happen to know if one list always contains them all.
You could use the following code:
ArrayList<String> Alist = new ArrayList<String>();
ArrayList<String> Blist = new ArrayList<String>();
Alist.add("gsm");
Alist.add("tablet");
Alist.add("pc");
Alist.add("mouse");
Blist.add("gsm");
Blist.add("something");
Blist.add("pc");
Blist.add("something");
for (String a : Alist)
{
for (String b : Blist)
{
if (a.equals(b))
{
System.out.println("Equals " + a);
break;
}
}
}
Output is:
Equals gsm
Equals pc
right now your comparing each element to all of the other ones. Do something like
for (int i = 0; i < Alist.size(); i++) {
if (!Alist.get(i).equals(Blist.get(i)) {
// print what you want
}
}
Thats of course assuming both lists have the same length.
Rather than writing code to manually compare list elements you might consider using Apache Commons Collections.
import org.apache.commons.collections.CollectionUtils;
List listA = ...;
List listB = ...;
Collection intersection = CollectionUtils.intersection(listA, listB);
import java.util.HashSet;
public class CheckSet<T> extends HashSet<T>{
#Override
public boolean add(T e) {
if (contains(e)) {
remove(e);
return true;
} else {
return super.add(e);
}
}
}
Add all elements of both of your lists to a CheckSet intance, and at the end it will only contain the ones not equal.
Here is one way:
public static boolean compare(List<String> first, List<String> second) {
if (first==null && second==null) return true;
if (first!=null && second==null) return false;
if (first==null && second!=null) return false;
if ( first.size()!=second.size() ) return false;
HashMap<String, String> map = new HashMap<String, String>();
for (String str : first) {
map.put(str, str);
}
for (String str : second) {
if ( ! map.containsKey(str) ) {
return false;
}
}
return true;
}
public static void main(String args[] ) throws Exception {
List<String> arrayList1 = new ArrayList<String>();
arrayList1.add("a");
arrayList1.add("b");
arrayList1.add("c");
arrayList1.add("d");
List<String> arrayList2 = new ArrayList<String>();
arrayList2.add("a");
arrayList2.add("b");
arrayList2.add("c");
arrayList2.add("d");
boolean isEqual = false;
if(arrayList1.size() == arrayList2.size()){
List<String> arrayListTemp = new ArrayList<String>();
arrayListTemp.addAll(arrayList1);
arrayListTemp.addAll(arrayList2);
HashSet<Object> hashSet = new HashSet<Object>();
hashSet.addAll(arrayListTemp);
if(hashSet.size() == arrayList1.size() &&
hashSet.size() == arrayList2.size()){
isEqual = true;
}
}
System.out.println(isEqual);
}
we can compare two different size arrayList in java or Android as follow.
ArrayList<String> array1 = new ArrayList<String>();
ArrayList<String> array2 = new ArrayList<String>();
array1.add("1");
array1.add("2");
array1.add("3");
array1.add("4");
array1.add("5");
array1.add("6");
array1.add("7");
array1.add("8");
array2.add("1");
array2.add("2");
array2.add("3");
array2.add("4");
for (int i = 0; i < array1.size(); i++) {
for (int j=0;j<array2.size();j++) {
if (array1.get(i) == array2.get(j)) {
//if match do the needful
} else {
// if not match
}
}
}
import java.util.Arrays;
public class ExampleContains {
public static boolean EligibleState(String state){
String[] cities = new String[]{"Washington", "London", "Paris", "NewYork"};
boolean test = Arrays.asList(cities).contains(state)?true:false;
return test;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(EligibleState("London"));
}
}