ArrayList comparison - java

I have an ArrayList made out of classes objects .The class has several String fields . In some classes
some fields that are the same must be removed from the ArrayList .
The field from the class that I need to check is sorted_participants which is set to be the same in some objects.
This is my Class:
public class Neo4jCompensation {
private String number_of_participants;
private String amount;
private String sorted_participants;
private String unsorted_participants;
private String href_pdf_compensation;
private String signed_by_all;
public Neo4jCompensation() {
this.number_of_participants = "";
this.amount = "";
this.sorted_participants = "";
this.unsorted_participants = "";
this.href_pdf_compensation = "";
this.signed_by_all = "";
}
public String getNumber_of_participants() {
return number_of_participants;
}
public void setNumber_of_participants(String number_of_participants) {
this.number_of_participants = number_of_participants;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getSorted_participants() {
return sorted_participants;
}
public void setSorted_participants(String sorted_participants) {
this.sorted_participants = sorted_participants;
}
public String getUnsorted_participants() {
return unsorted_participants;
}
public void setUnsorted_participants(String unsorted_participants) {
this.unsorted_participants = unsorted_participants;
}
public String getHref_pdf_compensation() {
return href_pdf_compensation;
}
public void setHref_pdf_compensation(String href_pdf_compensation) {
this.href_pdf_compensation = href_pdf_compensation;
}
public String getSigned_by_all() {
return signed_by_all;
}
public void setSigned_by_all(String signed_by_all) {
this.signed_by_all = signed_by_all;
}
}
So I have a first list filled with Classes:
ArrayList<Neo4jCompensation> results_list=new ArrayList<Neo4jCompensation>();
I thought that very good way to find the duplicates is to make a copy of a list , compare the two for the same class fields values and remove the duplicates .
This is how I find the duplicates
ArrayList<Neo4jCompensation> results_list1=new ArrayList<Neo4jCompensation>();
for(Neo4jCompensation pp:results_list)
{
Neo4jCompensation ss=new Neo4jCompensation();
ss.setAmount(pp.getAmount());
ss.setHref_pdf_compensation(pp.getHref_pdf_compensation());
ss.setNumber_of_participants(pp.getNumber_of_participants());
ss.setSigned_by_all(pp.getSigned_by_all());
ss.setSorted_participants(pp.getSorted_participants());
ss.setUnsorted_participants(pp.getUnsorted_participants());
results_list1.add(ss);
}
for (int i = 0; i < results_list.size(); i++) {
Neo4jCompensation kk=new Neo4jCompensation();
kk=results_list.get(i);
for (int j = 0; j < results_list1.size(); j++) {
Neo4jCompensation n2=new Neo4jCompensation();
n2=results_list1.get(j);
if(i!=j)
{
String prvi=kk.getSorted_participants().trim();
String drugi=n2.getSorted_participants().trim();
if(prvi.equals(drugi))
{
// results_list1.remove(j);
out.println("<p> Are equal su :"+i+" i "+j+"</p>");
}
}
}
}
Since I know that I can not loop and remove the elements from the ArrayList at the same
time i tried to use iterators like this ...
int one=0;
int two=0;
Iterator<Neo4jCompensation> it = results_list.iterator();
while (it.hasNext()) {
Neo4jCompensation kk=it.next();
Iterator<Neo4jCompensation> it1 = results_list1.iterator();
while (it1.hasNext()) {
Neo4jCompensation kk1=it1.next();
String oo=kk.getSorted_participants().trim();
String pp=kk1.getSorted_participants().trim();
if(one<two && oo.equals(pp))
{
it1.remove();
}
two++;
}
one++;
}
But it fails and gives me back nothing in ArrayList results_list1 - before removal with iterator it has in it the right elements . How to remove the objects from the array list that have the same field values as some other objects in the ArrayList .

Why not use .removeAll()
results_list1.removeAll(resultList);
This will require you to implement equals and hashcode within Neo4jCompensation
public class Neo4jCompensation {
//Omitted Code
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((number_of_participants == null) ? 0
: number_of_participants.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Neo4jCompensation other = (Neo4jCompensation) obj;
if (number_of_participants == null) {
if (other.number_of_participants != null)
return false;
} else if (!number_of_participants.equals(other.number_of_participants))
return false;
return true;
}
}

Another approach could be:
Overrride equals method in your Neo4jCompensation and check for the sorted_participants and return accordingly. Then use Set as a collection of your objects. Set does not allow duplicates and it uses equals to determine the equality.

for (int i = 0; i < results_list.size(); i++) {
Neo4jCompensation kk=new Neo4jCompensation();
kk=results_list.get(i);
for (int j = 0; j < results_list1.size(); j++) {
Neo4jCompensation n2=new Neo4jCompensation();
n2=results_list1.get(j);
if(results_list1.contains(kk) { results_list1.remove(j); }
}
But you may want to use a Set instead of a List or a data structure that maintains order, like a SortedMap, with a sentinel value.

Related

Java - TreeMap do not retrieves the key

I've topped with a problem I can not understand exactly what's happening here.
I operate with a TreeMap<Custom_class, TreeMap<Custom_class, Integer>>
Here is the fragment of code:
TreeMap<Coordenada, Integer> helper_tree;
boolean newLine = false;
for (Linea l : this.lineas) {
int helper = 0;
newLine = true;
Coordenada helper_co = null;
for (Coordenada c : l.getNodosLinea()) {
helper++;
if (!c.getEsEstacion() && !c.getEsCruce()) continue;
if (newLine) { map.putIfAbsent(c, new TreeMap<>()); helper_co = c; helper = 0; newLine = false; continue; }
helper_tree = new TreeMap<>();
helper_tree.put(helper_co, helper * 200);
map.put(c, helper_tree);
map.get(helper_co).put(c, helper * 200);
helper_co = c;
helper = 0;
}
}
In the execution the highlighted line fails, getting 0 entry for a key:
debug mode in intellij
And this is TreeMap structure:
TreeMap structure
I dont understand why in fails at .get(key) when the key Coordenada(12,2) is present. All before works just fine.
Coordenada class
public class Coordenada implements Comparable<Coordenada>{
private int[] coordenada = new int[2];
private boolean esEstacion = false;
private boolean esCruce = false;
public Coordenada(int[] coordenada){
this.coordenada[0] = coordenada[0];
this.coordenada[1] = coordenada[1];
}
public void setCoordenada(int[] coordenada) {
this.coordenada = coordenada;
}
public int[] getCoordenada() {
return coordenada;
}
public void switchEstacion(){
this.esEstacion = !this.esEstacion;
}
public void switchCruce() { this.esCruce = !this.esCruce; }
public boolean getEsEstacion() {
return this.esEstacion;
}
public boolean getEsCruce() { return this.esCruce; }
#Override
public boolean equals(Object coord){
Coordenada coordTemp = (Coordenada) coord;
if (this.coordenada[0] != coordTemp.coordenada[0])
return false;
if (this.coordenada[1] != coordTemp.coordenada[1])
return false;
return true;
}
#Override
public int compareTo(Coordenada o) {
if (this.coordenada[0] > o.coordenada[0] )
return 1;
if (this.coordenada[1] > o.coordenada[1] )
return 1;
if (this.coordenada[0] < o.coordenada[0])
return -1;
if (this.coordenada[1] < o.coordenada[1])
return -1;
return 0;
}
#Override
public String toString() {
return "(" + coordenada[0] + ", " + coordenada[1] + ")";
}
}
Inserts perfectly Coordenada(12,2) and modifies previous helper_co = Coordenada(10,2)
debugger variables
Thanks for any help!
Look at your compareTo function
(0,1) compareTo (1,0) returns 1
(1,0) compareTo (0,1) returns 1
It's ambiguous.

Implementing a Doubly Linked List from a Sorted Array Bag (Data Structures)

it's my first time ever posting on StackOverFlow, because I'm truly desperate right now. I couldn't find an answer for my problem anywhere, so long story short, I have some kind of project for my Data Structures course. The project had 2 parts. The first part was implementing a Sorted Array Bag/ Sorted Collection for some problem. We are using java.
The second part is where I do actually have a lot of problems. So the main idea is implementing a doubly-linked list from the sorted-array bag/ sorted collection and in a way that I would just switch sorted array bag with doubly-linked list in my main and everything should work the way it was working before.
The main thing about the SortedArrayBag is as far as I understand using a Comparator when you declare the SortedArrayBag in your main, and it looks like this:
SortedBag<Grupe> al = new SortedArrayBag<>(new ComparatorVot());
al.add(new Grupe("gr1", 5));
al.add(new Grupe("gr2", 7));
The sorted collection/sorted array bag was implemented by my teacher because there is no such data structure in Java, here is her implementation:
public class SortedArrayBag<T> implements SortedBag<T> {
private ArrayList<T> elemente;
private Comparator<T> relatie;
public SortedArrayBag(Comparator<T> rel) {
this.elemente = new ArrayList<>();
this.relatie = rel;
}
public void add(T elem) {
int index = 0;
boolean added = false;
while (index < this.elemente.size() && added == false) {
T currentElem = this.elemente.get(index);
if (relatie.compare(currentElem, elem) < 0) {
index++;
} else {
this.elemente.add(index, elem);
added = true;
}
}
if (!added) {
this.elemente.add(elem);
}
}
public void remove(T elem) {
boolean removed = this.elemente.remove(elem);
}
public int size() {
return this.elemente.size();
}
public boolean search(T elem) {
return this.elemente.contains(elem);
}
public Iterator<T> iterator() {
return this.elemente.iterator();
}
}
And the SortedBag interface looks like this
public interface SortedBag<T> {
public void add(T elem);
public void remove(T elem);
public int size();
public boolean search(T elem);
public Iterator<T> iterator();
}
Also in case it helps, the comparator looks like this:
public class ComparatorVot implements Comparator<Grupe> {
public int compare(Grupe o1, Grupe o2) {
Grupe gr1 = (Grupe) o1;
Grupe gr2 = (Grupe) o2;
if (gr1.getNrPersoane() / 2 + 1 == gr2.getNrPersoane() / 2 + 1) {
return 0;
} else if (gr1.getNrPersoane() / 2 + 1 > gr2.getNrPersoane() / 2 + 1) {
return 1;
} else {
return -1;
}
}
}
So, I tried my best implementing doublyLinkedList using a SortedArrayBag, this is what I did, also if it helps making my code more clear, prim=first, ultim=last, urmator=next, anterior=previous
import java.util.Iterator;
public class LDI {
private Nod prim;
private Nod ultim;
//private int lungime;
public LDI() {
this.prim = null;
this.ultim = null;
//this.lungime = 0;
}
public class Nod {
private int elem;
private int frecventa;
private Nod urmator;
private Nod anterior;
public Nod(int e, int f) {
this.elem = e;
this.frecventa = f;
this.urmator = null;
this.anterior = null;
}
}
public void add(int elem, int frecventa) {
Nod nodNou = new Nod(elem, frecventa);
nodNou.elem = elem;
nodNou.frecventa = frecventa;
if (prim == null) {
this.prim = nodNou;
this.ultim = nodNou;
} else if (frecventa <= prim.frecventa) {
nodNou.urmator = prim;
this.prim.anterior = nodNou;
this.prim = nodNou;
} else if (frecventa >= prim.frecventa) {
nodNou.anterior = prim;
for (; nodNou.anterior.urmator != null; nodNou.anterior = nodNou.anterior.urmator) {
if (nodNou.anterior.urmator.frecventa > frecventa)
break;
}
nodNou.urmator = nodNou.anterior.urmator;
if (nodNou.anterior.urmator != null) {
nodNou.anterior.urmator.anterior = nodNou;
}
nodNou.anterior.urmator = nodNou;
nodNou.anterior = nodNou.anterior;
}
}
public void remove() {
if (this.prim != null) {
if (this.prim == this.ultim) {
this.prim = null;
this.ultim = null;
} else
this.prim = this.prim.urmator;
this.prim.anterior = null;
}
}
public int size() {
int count = 0;
for (Nod nodNou = prim; nodNou != null; nodNou = nodNou.urmator)
count++;
return count;
}
public class MyIterator {
private Nod curent;
public MyIterator() {
this.curent = prim;
}
public void urmator() {
this.curent = this.curent.urmator;
}
public int getElem() {
return this.curent.elem;
}
public boolean valid() {
if (this.curent != null) {
return true;
} else {
return false;
}
}
}
public Iterator iterator() {
return new MyIterator();
}
}
The thing is, it doesn't work, I have no idea how to make my data structure able to receive the Comparator I used and also the Iterator doesn't work. If you have any idea how to make this work, please do help me.

Android how to sum the same object an ArrayList

Hello guys maybe my doubt is simple but could not solve.
My question is as follows:
I have an ArrayList of objects, these objects have number, name and value.
I would like to sum the values of these objects when the number and name are the same.
I thought of creating a new ArrayList to go the added values sum but to no avail.
My class:
private class ItemAdubacao {
float quantidadeProduto;
String produto;
int tanque_id;
public float getQuantidadeProduto() {
return quantidadeProduto;
}
public void setQuantidadeProduto(float quantidadeProduto) {
this.quantidadeProduto = quantidadeProduto;
}
public String getProduto() {
return produto;
}
public void setProduto(String produto) {
this.produto = produto;
}
public int getTanque_id() {
return tanque_id;
}
public void setTanque_id(int tanque_id) {
this.tanque_id = tanque_id;
}
}
I'm adding objects of this class in an ArrayList.
What I want is to go through this ArrayList checking objects that have Tanque_id and produto equal to sum the quantidadeProduto.
As I said I thought I'd create a new ArrayList and go adding the objects already added. For example:
public void finalizar() {
Adubacao adubacao = new Adubacao();
adubacaoArrayList = new ArrayList<>();
for (ItemAdubacao itemAdubacao : itemAdubacaoArrayList) {
if () {
}
}
adubacaoArrayList.add(adubacao);
}
But do not know how to IF
I solved my question, is not simple question IF
first added boolean equals in my class
public boolean equals(Object o) {
ItemAdubacao adubacao = (ItemAdubacao) o;
if (this.getTanque_id() == adubacao.getTanque_id() && (this.getProduto().equals(adubacao.getProduto()))) {
return true;
}
return false;
}
then I created an ArrayList to separate the duplicate objects and adding the sum of values
public void finalizar() {
ArrayList<ItemAdubacao> itensIguaisArrayList;
itensIguaisArrayList = new ArrayList<>();
adubacaoArrayList = new ArrayList<>();
for (ItemAdubacao itemAdubacao : itemAdubacaoArrayList) {
if (!itensIguaisArrayList.contains(itemAdubacao)) {
itensIguaisArrayList.add(itemAdubacao);
}
}
for (int i = 0; i < itensIguaisArrayList.size(); i++) {
float soma = 0;
for (ItemAdubacao linha : itemAdubacaoArrayList) {
if (linha.equals(itensIguaisArrayList.get(i))) {
soma += linha.getQuantidadeProduto();
}
}
itensIguaisArrayList.get(i).setQuantidadeProduto(soma);
}
}

Check ArrayList for duplicates

Class:
public class Variant
{
private String variant;
private String quantity;
//getters and setters
}
ArrayList:
ArrayList<Variant> variantList = getVariantsList();
Now I want to check whether variantList contains a duplicate entry of variant or not? Please note that variant having two entries with different quantity are to be considered as duplicates.
You can simply ovveride your equals method in your Variant class and provide all the rules for equality in that method.
#Override
public boolean equals(Object obj) {
..
Then you can use contains method or just pass it to a Set, that eliminates all your duplicates.
If you want variant having two entries with different quantity also considered as dup, then you can add that condition in your equals.
Override equals(Object obj) method and try to compare the object on variant and quantity.
Try to loop thru the variantList and do check for duplicity using variantList.contains(variant).
There are two things you need to do:
Override the equals() in your Variant class(minimal code below):
Please note that the below code only checks for quantity and not the variant prop. Your IDE might help you to generate the equals() as well.
#Override
public boolean equals(Object object) {
boolean isEqual = (this == object);
if(object instanceof Variant){
Variant variant = (Variant) object;
isEqual = this.quantity.equals(variant.quantity);
}else{
isEqual = false;
}
return isEqual;
}
Check if the List contains the object - which will use the equals() to check if both are equal.
for (Variant variant : variantList) {
if (variantList.contains(variant)) {
//do logic if its present
}
}
Just check one object with other objects of list
Override equals method in Variant class
#Override
public boolean equals(Object obj) {
if (obj != null) {
if (obj instanceof Variant) {
Variant temp = (Variant) obj;
return this.quantity.equals(temp.quantity); //for different quantity
} else {
return false;
}
}
return false;
}
Then check :
for (int i = 0; i < variantList.size(); i++) {
for (int j = 0; j < variantList.size(); j++) {
if (i != j) {
if (iList.get(i).equals(iList.get(j))) {
//logic when duplicate
break;
}
}
}
}
Follow the below guidelines:
Your Class Variant must override the equals method, since you define a duplicate condition based on quality hence in the equals method check for quality attribute value i.e.
public class Variant {
private String variant;
private String quantity;
public Variant(String variant, String quantity) {
this.variant = variant;
this.quantity = quantity;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((quantity == null) ? 0 : quantity.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Variant other = (Variant) obj;
if (quantity == null) {
if (other.quantity != null)
return false;
} else if (!quantity.equals(other.quantity))
return false;
return true;
}
}
Create a method which basically checking whether your list contains the duplicate entries(Variant) or not and return true and false accordingly:
private static boolean isListContainsDuplicateEntries(
ArrayList variantList) {
final List setToReturn = new ArrayList();
for (Variant v : variantList) {
if (!setToReturn.contains(v)) {
setToReturn.add(v);
} else {
return true;
}
}
return false;
}
Now, test the functionality:
public static void main(String[] args) {
Variant variant1 = new Variant("1", "100");
Variant variant2 = new Variant("2", "200");
Variant variant3 = new Variant("3", "200");
ArrayList<Variant> variantList = new ArrayList<>();
variantList.add(variant1);
variantList.add(variant2);
variantList.add(variant3);
System.out.println(Variant.isListContainsDuplicateEntries(variantList));
Output: true
You can use contains():
if (variantList.contains(**<some other Variant object>**)){
...
}
You can simply override your equals method in your Variant and try like this
List<Varient> list =getVariantsList();
System.out.println("here list size"+list.size());
Set<Varient> set = new HashSet<Varient>(list);
System.out.println("here"+set.size());
Create a varient Object:
public class Varient {
private String variant;
private String quantity;
public String getVariant() {
return variant;
}
public void setVariant(String variant) {
this.variant = variant;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Varient)) return false;
Varient varient = (Varient) o;
if (!quantity.equals(varient.quantity)) return false;
if (!variant.equals(varient.variant)) return false;
return true;
}
#Override
public int hashCode() {
int result = variant.hashCode();
result = 31 * result + quantity.hashCode();
return result;
}
}
Here is your main Program;
public class Test {
public static void main (String [] args){
// getVariantsList() here your list
List<Varient> list =getVariantsList();
Set<Varient> set = new LinkedHashSet<Varient>(list);
}
}
public class Variant {
private String variant;
private String quantity;
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((variant == null) ? 0 : variant.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Variant other = (Variant) obj;
if (variant == null) {
if (other.variant != null)
return false;
} else if (!variant.equals(other.variant))
return false;
return true;
}
public String getVariant() {
return variant;
}
public void setVariant(String variant) {
this.variant = variant;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public static void main(String[] args) {
// HashSet<Variant> set = new HashSet<>();
// LinkedHashSet<Variant> linkedSet = new LinkedHashSet<>(); // stores
// in input order
/*
* You can use treeset to store data in custom order, in this case
* lexicographically
*/
TreeSet<Variant> treeSet = new TreeSet<>(new VariantComparator());
}
}

Compare an Arraylist and give output

I have two ArrayLists. How can I compare the elements in the arraylists and create a new list with the results?
I need to iterate through the list to actually get its results and compare. How can I do it in Java?
Any help is appreciated.
Thanks
You can compare by implementing Comparator class.You can understand by below example in which Two Time class is getting compared.
class Time
{
int hours,minutes,seconds;
public Time(int hours,int minutes,int seconds)
{
this.hours=hours;
this.minutes=minutes;
this.seconds=seconds;
}
public int getHours()
{
return this.hours;
}
public int getMinutes()
{
return this.minutes;
}
public int getSeconds()
{
return this.seconds;
}
public String toString()
{
return String.format("%d:%02d:%02d %s",((hours==0||hours==12)? 12:hours%12),this.minutes,this.seconds,((hours>=12)?"PM":"AM"));
}
}
class TimeComparator implements Comparator<Time>
{
public int compare(Time t1,Time t2)
{
int hours=t1.getHours()-t2.getHours();
int minutes=t1.getMinutes()-t2.getMinutes();
int seconds=t1.getSeconds()-t2.getSeconds();
if(hours>0)
return 1;
else if(hours<0)
return -1;
if(minutes>0)
return 1;
else if(minutes<0)
return -1;
if(seconds>0)
return 1;
else if(seconds<0)
return -1;
return 0;
}
public boolean equals(Object obj)
{
return true;
}
}
After this you can use Collections class to use any method like sorting or search.
I hope that the following chunck of code will get you started.
import java.util.ArrayList;
class Compare {
public static void main(String[] args) {
ArrayList<String> a = new ArrayList<String>();
a.add("Hello");
a.add("Goodbye");
ArrayList<String> b = new ArrayList<String>();
b.add("Hello");
b.add("Bye");
if (a.size() != b.size()) {
System.out.println("Arrays must have the same size");
return;
}
ArrayList<Boolean> results = new ArrayList<Boolean>();
for(int i = 0; i < a.size(); ++i)
results.add(a.get(i).equals(b.get(i)));
for(int i = 0; i < a.size(); ++i)
System.out.println(results.get(i));
}
}

Categories

Resources