Returning Duplicates Arraylist - java

Below is a simple for loop I am using to try and go through and find the repeated ID's in a array list. The problem is that it only checks one index to the right so quite clearly if there is the same ID two, three or even four indexes across it will miss it and not report it as a repeated ID.
Obviously the goal of this code is to move through each index of the array list, get the ID and check if there are any other identical ID's.
Note for the below arraylist is...arraylist, the getId method simply returns the user ID for that array object.
for (int i=0; i<arraylist.size()-1; i++) {
if (arraylist.get(i).getId() == arraylist.get(i+1).getId()) {
System.out.println(arraylist.get(i).getId());
}
}
What I've tried and keep coming back to is to use two embedded for loops, one for iterating through the array list and one for iterating through an array with userIDs. What I planned on doing is checking if the current arraylist ID was the same as the array with 'pure' IDs and if it wasn't I would add it to the array of 'pure IDs. It would look something like this in psudocode.
for i<-0 i<arraylist size-1 i++
for j<-0 j<pureArray size j++
if arraylist.getId(i) != pureArray[j] then
increment pureArray size by one
add arraylist.getId(i) to pureArray
In practice perhaps due to my poor coding, this did not work.
So any opinions on how I can iterate completely through my arraylist then check and return if any the gotten IDs have multiple entries.
Thank you.

Looking at leifg's answer on this similar question, you can use two sets, one for duplicates and one for everything else, and you can Set#add(E), which "returns true if this set did not already contain the specified element," to determine whether or not the element is a duplicate. All you have to do is change the sets generics and what you are adding to them:
public Set<Integer> findDuplicates(List<MyObject> listContainingDuplicates)
{
// Assuming your ID is of type int
final Set<Integer> setToReturn = new HashSet();
final Set<Integer> set1 = new HashSet();
for (MyObject object : listContainingDuplicates)
{
if (!set1.add(object.getID()))
{
setToReturn.add(object.getID());
}
}
return setToReturn;
}

For the purpose of getting duplicates, nested for loop should do the job, see the code below. One more thing is what would you expect this nested for loop to do.
Regarding your pseudocode:
for i<-0 i<arraylist size i++
for j<-i+1 j<arraylist size j++
if arraylist.getId(i) != arraylist.getId(j) then
add arraylist.getId(i) to pureArray
1) Regarding j<- i+1, with every iteration you do not want to compare the same thing many times. With this set up you can make sure you compare first with others, then move to second and compare it to the rest (not including first because you already did this comparison) etc.
2) Incrementing your array every single iteration is highly impractical as you will need to remap and create a new array every single iteration. I would rather make sure array is big enough initially or use other data structure like another ArrayList or just string.
Here is a small demo of what I did, just a quick test, far no perfect.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// create a test array with ID strings
ArrayList test = new ArrayList<>();
test.add("123");
test.add("234");
test.add("123");
test.add("123");
String duplicates = "";
for(int i = 0; i < test.size(); i++) {
for(int j = i+1; j < test.size(); j++) {
// if values are equal AND current value is not already a part
// of duplicates string, then add it to duplicates string
if(test.get(i).equals(test.get(j)) && !duplicates.contains(test.get(j).toString())) {
duplicates += " " + test.get(j);
}
}
}
System.out.println(duplicates);
}
}
Purely for the purpose of finding duplicates, you can also create a HashSet and iteratively add the objects(ID's in your case)to the HashSet using .add( e) method.
Trick with HashSet is that it does not allow duplicate values and .add( e) method will return false if the same value is passed.
But be careful of what values(objects) you are giving to the .add() method, since it uses .equal() to compare whatever you're feeding it. It works if you pass Strings as a value.
But if you're giving it an Object make sure you override .equals() method in that object's class definition (because that's what .add() method will use to compare the objects)

Related

Compare and match arrays with different sizes

I have a couple of arrays with different sizes; say, array A and array B.
Array A
[chery, chery, uindy, chery, chery]
Array B
[chery, uindy]
Need to check whether the values present in Array A is available in Array B or not. In the above example, all the values in Array A is available in Array B. Please help this out with the Java code. Thanks!
You can convert your arrays to a List and then use the containsAll method to see if a particular list contains all elements described in another list.
You would get better performance out of it if they were Sets instead.
Example:
List<String> firstList = Arrays.asList("chery", "chery", "unid", ...);
List<String> secondList = Arrays.asList("chery", "unid", ...);
System.out.println(secondList.containsAll(firstList));
If the performance of this method in particular is getting a bit dodgy, then consider converting the lists into Sets instead:
Set<String> firstSet = new HashSet<>(Arrays.asList("chery", "chery", "unid", ...));
In the example I am using integers but can be used for other types also with slight modifications.
First put a loop on array A elements.
for(int i =0; i<A.length(); i++)
{
//this loop will transverse with all elements in array A.
}
Now inside this for loop make another for loop which transverse through elements of loop B.
for(int i =0; i<A.length(); i++)
{
for(int j=0; j<B.length();j++)
{
if(A[i] == B[j])
{ System.out.println("this element is in array A and B"); }
}
}
Now if you want to check if all elements of A are in B you can make a boolean. this boolean is true as long each element in A is found at least once in B. as soon as you find one element which is not present on both arrays you can exit.
Base on your requirement, you are going to find out if B is a superset of A (I mean the distinct values).
This can be easily done by one line like this:
String[] aArr = {.....};
String[] bArr = {.....};
return new HashSet<String>(Arrays.asList(bArr)).containsAll(Arrays.asList(aArr));
In brief, make B a Set, and check if B set contains all values of A
so, if A = {Apple, Apple, Banana, Cherry} and B = {Apple, Banana, Cherry, Pineapple}, it will return true (that's the behavior base on your description)
For arrays of Strings :
for (String str : array1)
{
System.out.println(ArrayUtils.contains(array2, str);
}
An array is not a good data structure for doing this. A Set is better. So convert your two arrays to Set objects, then simply use Set.equals(). Either do the conversion by creating new objects just before the comparison, or use a Set everywhere.
Set<String> setA = new HashSet<>(Arrays.asList(new String[]{"chery", "chery", "uindy", "chery", "chery"}));
Set<String> setB = new HashSet<>(Arrays.asList(new String[]{"chery", "uindy"}));
System.out.println("Sets are equal: " +setA.equals(setB));
The equals method of AbstractSet says
Compares the specified object with this set for equality. Returns true
if the given object is also a set, the two sets have the same size,
and every member of the given set is contained in this set. This
ensures that the equals method works properly across different
implementations of the Set interface. This implementation first checks
if the specified object is this set; if so it returns true. Then, it
checks if the specified object is a set whose size is identical to the
size of this set; if not, it returns false. If so, it returns
containsAll((Collection) o).

Java for each statement

I'm really good with VB and I have a project where I need to check an array. If the same item in an array exists twice or more it needs to be changed to an item that doesn't exist. Now I'm in a class where they're making us use Java for this project.
I was wondering what is the equivalent of a for each loop in Java? I checked the JavaDocs and it only had info for the regular for loop, I didn't notice any section that said anything about a for each loop.
It's more subtle in Java than VB. You can find the official docs in the Oracle documentation here (towards the bottom):
Java For Loops
The provided example is:
// Returns the sum of the elements of a
int sum(int[] a) {
int result = 0;
for (int i : a)
result += i;
return result;
}
Hope that helps. Be careful not to remove or add elements inside the loop or you will get a Concurrent Modification Exception.
try
String arr [] = // you decide how this gets initialized
for (String obj: arr) {
}
This is called "iterating over collections". An array can be implicitly converted to a collection, so you can iterate over an array in the same way, using the "enhanced for-loop".
List<String> names = new LinkedList<>();
// ... add some names to the collection
for(name:names) {
System.out.println(name);
}
I'm not sure if VB has collections - they are a big part of Java and I recommend you look into them.
Of course this changes a bit in Java 8, although you'll notice a collection is still the backbone of forEach().
List<String> names = new LinkedList<>();
// ... add some names to the collection
names.forEach(name -> System.out.println(name));
A for each loop (also known as the enhanced for loop) is as follows:
for (String name : names) {
// here, the loop will work over each element of 'names',
// with the variable name with which to access each element
// being 'name', and output it
System.out.println(name);
}
A normal for loop is as follows:
for (int i = 0; i < max; i++) {
// here, i will iterate until max, then the loop will stop.
// any array access here has to be done manually using i, which increments.
}
If insertion order from the names array is important, keep adding the objects to a LinkedHashSet<String>, then with either a for loop or enhanced for loop or iterator, go over your list of names and add each of them to the LinkedHashSet. If the add method, passing in your name, returns false, generate a new name and add that.
If insertion order is not important, use a HashSet<String> instead.
At the end, convert back to an array if it is important (String[] bla = map.toArray(new String[0])), or output the toString() of the map.

Adding value to java array in the right place

I am trying to write a little program that will contain a array of profiles of people and I am stuck on the method for adding the profiles, as I would like them to be added in correct place so it doesn't need to be sorted. For example
If I have a array with 3 profiles
Potter, H
Smith, T
Warren, B
And I want to add Summer, P I would like it to be added right between the 1st and 2nd index
Before anyone asks I haven't got much code for this as I am still thinking on how to search the array and say where the profile needs to be placed.
Any ideas are appreciated
(Also it needs to be a Array not a ArrayList or any other data structure)
If you want to use an array rather than a decent, appropriate data structure, then use Arrays.binarySearch() to find the appropriate location. But you'll have to shift all the subsequent elements.
Whatever you are talking about is best done by the LinkedList http://docs.oracle.com/javase/6/docs/api/java/util/LinkedList.html
Since you want to use Array only, then as you know arrays have a constant number of elements that you declare. So I recommend you to create a temporary ArrayList and then copy those elements into an array that you want. Here how it's done
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
String[] yourInitialArray = { "Potter, H", "Smith, T", "Warren, B" };
// Creating a temporary ArrayList
ArrayList<String> temporary = new ArrayList<String>();
for (int i = 0; i < yourInitialArray.length; i++) {
if (i != 1) {
temporary.add(yourInitialArray[i]);
} else {
temporary.add("Summer, P");
temporary.add(yourInitialArray[i]);
}
}
yourInitialArray = new String[temporary.size()];
for (int j = 0; j < temporary.size(); j++) {
yourInitialArray[j] = temporary.get(j);
System.out.println(yourInitialArray[j]);
}
}
}
try to adding normally after that sort the list.It is better to use
First of all, I would highly recommend using the Collections framework List over the Arrays. because it provides the lot of flexibility and improvements over using normal arrays
and for your solution, i would recommend using the LinkedList. This provides the method add(int index, E element ) for inserting the element at specific location and it is very efficient

How To Remove an item from an Array and move everything else down? [duplicate]

This question already has answers here:
Removing an element from an Array (Java) [duplicate]
(15 answers)
Closed 9 years ago.
I have an array of Contact objects that has a MAX of 50 Contacts, but will have much less, so the array is initialized with a size of 50. But I need my method to remove the Contact and shift everything after it up. What I have seems to work at times, but not every time.
public Contact remove(String lstnm)
{
int contactIndex = findContactIndex(lstnm); // Gets the index of the Contact that needs to be removed
Contact contactToBeRemoved;
if(contactIndex == -1) // If the Contact is not in the Array
{
contactToBeRemoved = null;
}
else
{
contactToBeRemoved = Contact_List[contactIndex]; // Assigns the Contact that is going to be removed
for(int i = contactIndex; i < numContacts; i++) // From where the Contact was removed to the last Contact in the list
{
Contact_List[i] = Contact_List[i + 1]; // Shift all of the Contacts after the one removed down
}
numContacts -= 1; // One Contact is removed from the total number of Contacts
}
return contactToBeRemoved;
}
Arrays a fixed size you cannot resize them. ArrayList on the other hand auto resize each time you add a element.
So if I have a Array of 5 I can put 5 items in it, no more no less. One thing you can do is set objects in the Array to be null or 0.
Edit: With regards to your comment, just sort the Array. Look up a easy bubble sort algorithm in Java.
try
System.arraycopy(contactList, contactIndex + 1, contactList, contactIndex, contactList.length - contactIndex - 1);
Note that System.arraycopy is the most efficient way to copy / move array elements
your code would give exception at numContacts'th iteration since i+1 will go beyond size of array.
for(int i = contactIndex; i < numContacts-1; i++)
{
Contact_List[i] = Contact_List[i + 1];
}
Contact_List[Contact_List.length-1] = null;
Ps: its a very bad practice to use Array in such scenario, consider using ArrayList instead.
Why don't you convert your array into a List and use the remove(Object o) method that does exactly what you describe?
It would save you some time and some testing.
for such purpose use ArrayList
ArrayList<Contact> array = new ArrayList<Contact>(50);
creates a dynamic array with initial capacity of 50 (this can increase as more elements gets added to the ArrayList)
array.add(new Contact());
array.remove(contact); //assuming Contact class overrides equals()
ArrayList internally maintains an array and does re-sizing, restructuring as the elements are added or removed from it.
You can also use Vector<Contact> which is similar data-structure, but thread safe.
Array's become pretty useless when you know how to use arrayList, in my opinion. I suggest using arrayLists.
ArrayList tutorial
do like this when creating ht econtact arrayList:
import java.util.ArrayList;
public static void main(String args[]){
ArrayList<Contact> contacts = new ArrayList();
contacts.add(new Contact());
}
Use arrayLists, its the best way. Read tutorials, the are plenty of them.
I suggest it cause arralist are dynamic, that means you can add and remove items and it resized itself for you.
Hope I could help even if my answers isnt very complete
use collection rather than array so that you dont have to do all the shifting processes!
collection automatically shifts the elements and you dont have to worry about it!
you may do as follow,
ArrayList<Contact> list=new ArrayList<Contact>();
Contact c=new Contact();
Contact.Add(Contact);
Contact.remove(Contact);
and any more behaviours are available in ArrayList!
you may write you remove method as follows
public Contact remove(String lstnm)
{
Contact c=new Contact(1stnm);
Contact contactToBeRemoved=list.get(1);
List.remove(c);
return contactToBeRemoved;
}
but you have to override the equal() and compareTo() method of the object class in the Contact class!
otherwise nothing will work properly!

Java ArrayList search

I have an ArrayList of type String. I want to determine whether any element of this ArrayList starts with a specified string and if the ArrayList contains this element, then I want to get the index of this element. In addition, I do not want to loop this ArrayList to get the index of that element.
For example :
ArrayList<String> asd = new ArrayList<String>(); // We have an array list
//We filled the array list
asd.add("abcc trtiou");
asd.add("aiwr hiut qwe");
asd.add("vkl: gtr");
asd.add("aAgiur gfjhg ewru");
Now, I want to get the index of the element vkl: gtr by using vkl: without looping array list.(searching also should be case insensitive, so, using vkl: and VkL: should give the index of vkl: gtr)
How can I do this ?
Thanks in advance.
You have to loop the ArrayList. You cant possibly access just a single index and be guaranteed it is what you're looking for.
Also, you should consider using another data structure if a lot of searching is involved. Searching an ArrayList takes O(n)time while something like a red-black tree can be done in O(log n).
If you know before program execution the strings used to locate the items in the structure, consider using a HashMap. You can access the items in O(1).
If none of these solutions suit your particular problem expand on your answer with what you're trying to do, we could provide a better answer as to how you'd locate your items with minimal search time.
This is as far as you can get with your requirement if you're not looking to perform loop and search against the string objects held in the arraylist.
if(asd.contains("vkl: gtr"))
{
int index=asd.indexOf("vkl: gtr");
}
or simply:
int index = Arrays.binarySearch(asd.toArray(), 0, asd.size()-1, "vkl: gtr");
If performing loop in your calling method is what you're looking to avoid then, alternative you can create a class which extends ArrayList and have a method which does the index lookup.
class MyArray extends ArrayList<String>
{
public int getIndexOf(String o)
{
for (int i = 0; i < size(); i++)
{
if (get(i).contains((String) o)) return i;
}
return -(size() - 1);
}
}
Then from your calling program do:
public void foo()
{
MyArray asd = new MyArray();
asd.add("abcc trtiou");
asd.add("aiwr hiut qwe");
asd.add("vkl: gtr");
asd.add("aAgiur gfjhg ewru");
int index = asd.getIndexOf("vkl:");
}
for(int i=0; i < asd.size(); i++) {
String s = asd.get(i);
//search the string
if(found) {
return i
}
}
return -1
I don't really understand if you are looking for something like key-value pairs or single string entry search.
If you are looking for the first one you should use Map instead of a simple array if you want to search for a key
Here you can put a pair using
put(Object key, Object value)
and the getting the value of a specified key with
get(Object key)
If you are looing only for a quick way of finding a part of string into an array you have to read all indexes and compare strings one by one using stringToCompare.equalsIgnoreCase(otherStringToCompare). Note that this will throw an exception if stringToCompare is NULL

Categories

Resources