ArrayList Java String remove doesnt delete - java

I am working with Arraylist of objects.
while i already succeeded in delete values from Arraylist while they are numeral.
i'm having trouble delete from arraylist while they are String
here is the example :
public class ArrayListDemo {
public static void main(String[] args) {
// create an empty array list with an initial capacity
ArrayList<Namer> arrlist = new ArrayList<Namer>( );
// use add() method to add values in the list
arrlist.add(new Namer("1","A","G"));
arrlist.add(new Namer("2","E","G"));
arrlist.add(new Namer("3","F","G"));
System.out.println("Size of list: " + arrlist.size());
// let us print all the values available in list
for (Namer value : arrlist) {
System.out.println("age = " + value.age);
}
arrlist.remove("3");
System.out.println("Now, Size of list: " + arrlist.size());
for (Namer value : arrlist) {
System.out.println("age = " + value.age); //System.out.println("Value = " + value);
}
}
}
and the result of running it proof it doesnt deleted the spesific row
i need to delete if with String and cant use number as "Key" .
Size of list: 3
age = 1
age = 2
age = 3
Now, Size of list: 3
age = 1
age = 2
age = 3
what can i make it to work with String in order to delete ?
if that's help
this is the object of arrayList
public class Namer
{
// instance variables - replace the example below with your own
public String age;
public String name;
public String L_name;
public Namer(String a, String na , String Lname)
{
// initialise instance variables
age =a;
name=na;
L_name=Lname;
}
}

You have Namer objects in your ArrayList, not Strings. When you call remove("3"), the ArrayList will look for an object that returns true when equals is called on it with "3". Of course, no String will compare equals with any Namer.
You must do the comparison yourself with the name field, and remove the appropriate item. This can be done with an Iterator and its remove method.

You have to use the object or the index to remove and you are not using either ...
Try this code :
arrlist.remove(2);
or
// create an empty array list with an initial capacity
ArrayList<Namer> arrlist = new ArrayList<Namer>( );
Namer namer1= new Namer("1","A","G");
Namer namer2= new Namer("2","E","G");
Namer namer3= new Namer("3","F","G");
// use add() method to add values in the list
arrlist.add(namer1);
arrlist.add(namer2);
arrlist.add(namer3);
arrlist.remove(namer3);

The method arrlist.remove(idx) takes as paramenter the (interger) index of the element to be removed from the array. There's no such thing as a "key" for ArrayLists.
You probably want to use java.util.Map<Integer,Namer>.

Related

Check whether the array contains more than 1 equivalent value

I have an array where i get the values as names of some students and the array is dynamically populates and it does not contain static values. Now what i want to check is that whether the array obtained has any same name. Here is some part of my code,
ArrayList<Student> rows;
for (Student name: rows) {
}
I dont know how to check. I have used compartor but it didnt work. Can anyone help. Inside the array I will get all student names
Use a list to store any duplicate names:
List<String> dups = new ArrayList<>();
and a set where you will store names:
Set<String> names = new HashSet<>();
A set contains only unique values.
Now iterate through your list
(I guess your Student class has a method like getName() to obtain the student's name):
for (Student student : rows) {
String studentname = student.getName();
if (!names.add(studentname) {
dups.add(studentname);
}
}
The method names.add() returns false when it's not possible for an item to be added to the set because it already exists in it.
So when it returns false it encountered a duplicate name and the name is added to the dups list.
When this loop finishes, you can find all the duplicate student names in the dups list and show them in a toast:
if (dups.size() > 0) {
StringBuilder sb = new StringBuilder("There are duplicates: ");
for (String studentname : dups) {
sb.append(studentname).append(", ");
}
String msg = sb.toString();
msg = msg.substring(0, msg.length() - 2);
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
A way to check it is to convert your list to a set and check if the size got reduced (because Sets do not accept duplicate values), something like :
ArrayList<Student> rows;
Set<Student> set = new HashSet<Student>(rows);
if(set.size() < rows.size()){
// In this case you have repeated values in the list
}
Note that it depends on your equals method of the Student class to determine how Students are compared, so since you are checking againist their names you might have this equals method inside your Student class:
#Override
public boolean equals(Object obj) {
if( obj instanceof Student) {
return (obj.name.equals(name));
}
return false;
}
Store the data in HashMap with key as studentName and value as student object
Map studentMap = new HashMap<>()
If you add the data with same key again , the data gets updated
studentMap.put(studentName, Student)
To check if key exists and update accordingly
if(studentMap.containsKey(studentName)){
// logic if key already exists
}else{
//logic if key doesn't exists
}
If you want list instead of map , then get list from map
List studentList = new ArrayList(studentMap.values())
Check this sample java class used to count no of duplicate elements.
public class CountDuplicate {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("aaa");
arrayList.add("bbb");
arrayList.add("aaa");
arrayList.add("bbb");
arrayList.add("ccc");
arrayList.add("bbb");
arrayList.add("ccc");
arrayList.add("aaa");
arrayList.add("ccc");
arrayList.add("bbb");
HashSet<String> hsUnique = new HashSet<String>(arrayList);
for (String str : hsUnique) {
System.out.println(Collections.frequency(arrayList, str) +" times "+ str);
}
}
}

How to find duplicates within an array - Java

I currently have this code that is fully functioning in Java. It takes a string, turns it into an array and removes all of the duplicates. I decided to use the string "a sailor went to sea sea sea to see what he could see see see but all that he could see see see was the bottom of the deep blue sea sea sea". I used this as it has a large number of duplicates.
To add to the code I would like to be able to get the positions of all the elements in the array, I believe the correct method is through nested loops but I am not sure how to accomplish this. If anyone has some guidance or even general ideas i would be great full.
Here is the current code:
static ArrayList<String> removeDuplicates(String[] list) {
// Store unique items in result.
ArrayList<String> result = new ArrayList<>();
// Record encountered Strings in HashSet.
HashSet<String> set = new HashSet<>();
// Loop over argument list.
for (String item : list) {
// If String is not in set, add it to the list and the set.
if (!set.contains(item)) {
result.add(item);
set.add(item);
}
}
return result;
}
public static void main(String[] args) {
String sea1 = "A sailor went to sea sea sea, to see what he could see see see, but all that he could see see see, was the bottom of the deep blue sea sea sea";
String sea2 = sea1.toLowerCase();
String sea3 = sea2.replaceAll("[\.:;,\"!\?]", " "); //remove punctuation + sets to lower case
String sea4 = sea3.replaceAll(" ", " ");
String sea5 = sea4.replaceAll(" ", ",");
String sea6 = sea5.replaceAll("'", " ");
String sea7 = sea6.replaceAll(" ", "");
System.out.println("Here is the string: " + sea7);
String[] sealist = sea7.split(",");
System.out.println("Here is the string 'end' with duplicates removed: ");
// Remove duplicates from ArrayList of Strings.
ArrayList<String> unique = removeDuplicates(sealist);
for (String element : unique) {
System.out.println("- " + element);
}
}
}
Your code is good, but if the order is critical, why not use a LinkedHashSet?
Add the elements to the linkedhashset, then to get them back in the order they were added, simply get the entries as toString(). You'll have a comma delimiting the returned words, but they can easily be removed. It will look like "[a,sailor,went,to,sea,see,what ...]"
static ArrayList<String> removeDuplicates(String[] list) {
// Record encountered Strings in HashSet.
LinkedHashSet<String> set = new LinkedHashSet<>();
// Loop over argument list.
for (String item : list) {
// Left this if statement in for clarity (!needed)
if (!set.contains(item)) {
set.add(item);
}
}
String result= set.toString();
return(result.split(",");
}

Java - How to use a for each loop to check the different occurrences of a value in a list of objects

Sorry if the title isn't clear, I wasn't sure how to word it. I have an arraylist of objects and within each of these objects I store an integer value referring to a category and one referring to an ID.
I want to find the number of unique combinations of category and IDs that there are.
So at the moment I have
for(Object object: listofObjects){
//For each unique type of object.getID
//For each unique type of object.getCategory
//Add 1 to counter
}
I can't figure out how to do this. Doing things like for(int cat: object.getCategory()) brings up an error.
I can add the values to a new list within the initial for each loop like so,
ArrayList<Integer> aList= new ArrayList<Integer>();
for (Object object : spriteExplore) {
aList.add(object.getCategory());
}
for (int cat : aList) {
testCounter++;
}
but this obviosuly does not take into account uniqueness and also makes it awkward for factoring in the other variable of ID.
I feel like there is probably some easier work around that I am missing. Any advice?
Thanks in advance.
So you list of UserDefine object in ArrayList and you want to find unique Object.Just create set from list.
For e.g Suppose you have
List<Customer> list=new ArrayList<Custeomer>();
list.add(new Customer("A",12));
list.add(new Customer("B",13));
list.add(new Customer("A",12));
now
create set From this list
Set<Customer> set = new HashSet<Customer>(list);
this will have unique Customer
IMP : dont forget to override equals and hashcode method for Customer
Your best approach would be storing the data correctly.
It's possible that you still need to store non-unique items, if that's so - continue using an ArrayList, but in addition, use the following:
Override the hashcode & equels function as shown in this link:
What issues should be considered when overriding equals and hashCode in Java?
Then, use a Set (HashSet would probably be enough for you) to store all your objects. This data structure will disregard elements which are not unique to elements already inside the set.
Then, all you need to do is query the size of the set, and that gives you the amount of unique elements in the list.
I don't know any library that does this automatically, but you can do it manually using sets. Sets will retain only unique object so if you try to add the same value twice it will only keep one reference.
Set<Integer> categories = new HashSet<Integer>();
Set<Integer> ids= new HashSet<Integer>();
for (Object object : listofObjects) {
categories.add(object.getCategory());
ids.add(object.getID());
}
Then you get the number of unique categories / ids by doing
categories.size()
ids.size()
And all your unique values are stored in the sets if you want to use them.
I would look into using a (Hash)Map<Integer, Integer>. Then just have 1 foreach loop, checking to see if the value of Map<object.getId(), object.getCategory()> is null by checking if map.get(object.getId()) is null - if it is, then this pair does not exist yet, so add this pair into the map by using map.put(object.getId(), object.getCategory()). If not, do nothing. Then at the end, to find the number of unique pairs you can just use map.size()
Hope this helps
Map<Integer,List<Integer>> uniqueCombinations = new HashMap<Integer,List<Integer>>();
for (Object object : listofObjects) {
if(uniqueCombinations.get(object.getCategoryId())==null) {
uniqueCombinations.put(object.getCategoryId(), new LinkedList<Integer>);
}
uniqueCombinations.get(object.getCategoryId()).add(object.getId());
}
return uniqueCombinations.size()
I believe you want unique combinations of both category and id, right?
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class SO {
class MyObject{
private int id;
private int category;
private String name;
private MyObject(int id, int category,String name) {
super();
this.id = id;
this.category = category;
this.name = name;
}
protected int getId() {
return id;
}
protected int getCategory() {
return category;
}
#Override
public String toString() {
return "MyObject [id=" + id + ", category=" + category + ", name=" + name + "]";
}
}
public static void main(String[] args) {
SO so = new SO();
List<Object> listofObjects = new ArrayList<Object>();
listofObjects.add(so.new MyObject(1,1,"One"));
listofObjects.add(so.new MyObject(1,1,"Two"));
listofObjects.add(so.new MyObject(1,2,"Three"));
Map<String,List<MyObject>> combinations = new HashMap<String,List<MyObject>>();
for(Object object: listofObjects ){
//For each unique type of object.getID
//For each unique type of object.getCategory
//Add 1 to counter
if (object instanceof MyObject){
MyObject obj = (MyObject)object;
String unique = obj.id+"-"+obj.category;
if (combinations.get(unique) == null){
combinations.put(unique, new ArrayList<MyObject>());
}
combinations.get(unique).add(obj);
}
}
System.out.println(combinations);
//counts
for(Entry<String,List<MyObject>> entry:combinations.entrySet()){
System.out.println(entry.getKey()+"="+entry.getValue().size());
}
}
}
Use the Hashmap to save occurence. Dont forget to implement hashcode und equals Methods. You can generate them if you work with Eclipse IDE.
public static void main(String[] args) {
List<MyObject> myObjects = Arrays.asList(new MyObject(1, 2), new MyObject(2, 3), new MyObject(3, 4), new MyObject(3, 4));
Map<MyObject, Integer> map = new HashMap<>();
for (MyObject myObject : myObjects) {
Integer counter = map.get(myObject);
if(counter == null){
counter = 1;
} else {
counter = counter + 1;
}
map.put(myObject, counter);
}
long uniqueness = 0;
for(Integer i : map.values()){
if(i == 1){
++uniqueness;
}
}
System.out.println(uniqueness);
}
The last part can be replaced by this one line expression if you are working with Java 8:
long uniqueness = map.values().stream().filter(i -> i == 1).count();

Iterating through double collections in Java

I'm a Java beginner, so please bare with possibly silly or trivial questions.
I have two collections (array lists or hashtables) and I want to compare each and every element of the first collection to each and every element of the second collection.
I wrote the following code, but this only compares element 1 of the first collection to element 1 of the second collection, element 2 of the first collection with element 2 of the second collection, etc., so I am missing most of the comparisons that I want to make. Can you please help me out?
public class IteratorDemo_1 {
public static void main(String args[]) {
// Create two array lists:
ArrayList alLetters = new ArrayList();
ArrayList alNumbers = new ArrayList();
// Add elements to the array lists:
alLetters.add("C");
alLetters.add("B");
alLetters.add("Z");
alLetters.add("X");
alNumbers.add("1");
alNumbers.add("6");
alNumbers.add("3");
alNumbers.add("7");
// Use iterator to display the contents of 'al':
System.out.println("Original contents of 'alLetters': ");
Iterator itrL = alLetters.iterator();
System.out.println("Original contents of 'alNumbers': ");
Iterator itrN = alNumbers.iterator();
while(itrL.hasNext()){
while(itrN.hasNext()){
Object elementL = itrL.next();
Object elementN = itrN.next();
boolean result = elementL.equals(elementN);
System.out.println(result);
System.out.println(elementL + " ");
System.out.println(elementN + " ");
}
}
System.out.println();
}
}
while(itrL.hasNext()){
Object elementL = itrL.next();
while(itrN.hasNext()){
Object elementN = itrN.next();
boolean result = elementL.equals(elementN);
System.out.println(result);
System.out.println(elementL + " ");
System.out.println(elementN + " ");
}
itrN = alNumbers.iterator();
}
Try the following:
while(itrL.hasNext()){
Object elementL = itrL.next();
Iterator itrN = alNumbers.iterator();
while(itrN.hasNext()){
Object elementN = itrN.next();
boolean result = elementL.equals(elementN);
System.out.println(result);
System.out.println(elementL + " ");
System.out.println(elementN + " ");
}
}

Why do my array.size() give wrong value?

I have an instance of ArrayList named array.
When I parse some JSON data it will store it all in array.
When I do a System.out.println(array); it will list a long list of items, around 30, but when I write System.out.println(array.size); it will give the value one.
How come it only gives me the value 1 when the list contains at least 30 values?
My code for this:
public void setLocationName (String name) {
array = new ArrayList<String>();
array.add(name);
System.out.println(array); //This return a long list
System.out.println(array.size()); //But this only return the value 1
}
public String[] getLocationName() {
String tArray[] = null;
for (int i = 0; i < array.size(); i++){
System.out.println(i);
tArray = array.toArray(new String[i]);
}
return tArray;
}
}
The long list :
[Brunnsparken, Göteborg]
[Brunnsgatan, Göteborg]
[Brunnslyckan, Lerum]
[Brunnsbotorget, Göteborg]
[Brunnsnäs, Ulricehamn]
[Brunnshult, Mellerud]
[Brunnsdal, Skövde]
[Brunns skola, Ulricehamn]
[Brunnsgården, Kungälv]
[Brunns kyrka, Ulricehamn]
[Boråsparken, Borås]
[Stadsparken, Ulricehamn]
[Lysekilsparken, Lysekil]
[Mössebergsparken, Falköping]
[Dalaborgsparken, Vänersborg]
[Rösparken, Åmål]
[Lillhagsparken Norra, Göteborg]
[Lillhagsparken Södra, Göteborg]
[Sylte Ryrbäcksparken, Trollhättan]
[Skogstomtsparken, Borås]
[Svinesundsparken, Norge]
[Håjumsparken, Trollhättan]
[Eriksdalsparken, Bollebygd]
[Fridhemsparken, Lidköping]
My result will be that only one item from the list will be returned in the tArray but I wanna return the whole list.
How to solve this?
Java doesn't understand Json and basically what you're doing is add a string to an array
this.array.add(name); ---> add one value to the array, therefore the size is just one
you may need to use a specific Json library to parse the data in to an java arraylist.
regards
Look like you need to parse the String into pairs.
Looks to me like a Map might be the most appropriate structure to store the data in - I presume the first part from the value is unique.
Regex is probably the best approach to parsing the data:
public static void main(String[] args) {
final String data = "[Brunnsparken, Göteborg]\n"
+ "[Brunnsgatan, Göteborg]\n"
+ "[Brunnslyckan, Lerum]\n"
+ "[Brunnsbotorget, Göteborg]\n"
+ "[Brunnsnäs, Ulricehamn]\n"
+ "[Brunnshult, Mellerud]\n"
+ "[Brunnsdal, Skövde]\n"
+ "[Brunns skola, Ulricehamn]\n"
+ "[Brunnsgården, Kungälv]\n"
+ "[Brunns kyrka, Ulricehamn]\n"
+ "[Boråsparken, Borås]\n"
+ "[Stadsparken, Ulricehamn]\n"
+ "[Lysekilsparken, Lysekil]\n"
+ "[Mössebergsparken, Falköping]\n"
+ "[Dalaborgsparken, Vänersborg]\n"
+ "[Rösparken, Åmål]\n"
+ "[Lillhagsparken Norra, Göteborg]\n"
+ "[Lillhagsparken Södra, Göteborg]\n"
+ "[Sylte Ryrbäcksparken, Trollhättan]\n"
+ "[Skogstomtsparken, Borås]\n"
+ "[Svinesundsparken, Norge]\n"
+ "[Håjumsparken, Trollhättan]\n"
+ "[Eriksdalsparken, Bollebygd]\n"
+ "[Fridhemsparken, Lidköping]";
final Pattern pattern = Pattern.compile("\\[([^,]++),\\s++([^\\]]++)\\]");
final Matcher matcher = pattern.matcher(data);
final Map<String, String> items = new TreeMap<>();
while (matcher.find()) {
items.put(matcher.group(1), matcher.group(2));
}
for (final Entry<String, String> entry : items.entrySet()) {
System.out.println(entry);
}
}
Output from this:
Boråsparken=Borås
Brunns kyrka=Ulricehamn
Brunns skola=Ulricehamn
Brunnsbotorget=Göteborg
Brunnsdal=Skövde
Brunnsgatan=Göteborg
Brunnsgården=Kungälv
Brunnshult=Mellerud
Brunnslyckan=Lerum
Brunnsnäs=Ulricehamn
Brunnsparken=Göteborg
Dalaborgsparken=Vänersborg
Eriksdalsparken=Bollebygd
Fridhemsparken=Lidköping
Håjumsparken=Trollhättan
Lillhagsparken Norra=Göteborg
Lillhagsparken Södra=Göteborg
Lysekilsparken=Lysekil
Mössebergsparken=Falköping
Rösparken=Åmål
Skogstomtsparken=Borås
Stadsparken=Ulricehamn
Svinesundsparken=Norge
Sylte Ryrbäcksparken=Trollhättan
You can the access the items by looping (as above) or by getting values from the Map by key. The TreeMap I have used will sort the data by key, you can also use a LinkedHashMap to store the data in insertion order.
You could also store the items in a List of tuple like structures.
public void setLocationName (String name) {
array = new ArrayList<String>();
array.add(name);
System.out.println(array); //This return a long list
System.out.println(array.size()); //But this only return the value 1
}
You are creating a new ArrayList each time you call this method:
array = new ArrayList<String>();
You could just remove the above line, however I suggest you rename the method as this is no longer a setter and you are in fact now adding to an existing list each time you call this method.
I suggest what you want to do is build your List before parsing to the setter, perhaps using a foreach loop (I'm not sure what kind of object you are working with) and simplify your setter (setLocationName) to accomodate.
So it would become:
public void setLocationName(ArrayList<String> names)
{
this.array = names;
System.out.println(array); //This return a long list
System.out.println(array.size()); //But this only return the value 1
}

Categories

Resources