I have a ListView with an arraylist with an unknown number of string elements. I want to change/modify every single one of these string items. The problem is that i dont know how many items there are since the user can change it.
I have a translate function that takes a string and returns a string. What i want to do is
arraylistelement1 = translate(arraylistelement1);
arraylistelement2 = translate(arraylistelement2);
...
and repopulate the listview arraylist with the new strings.
Whats a way to do this?
Iterate over the list and create a new list of translated options from the original then replace the contents of the original list with the new values. If you do the replacing while iterating you'll get ConcurrentModificationExceptions.
Use ListIterator.set:
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("s0", "s1", "s2"));
ListIterator<String> iter = list.listIterator();
while (iter.hasNext())
iter.set(translate(iter.next()));
for (String element : list)
System.out.println(element);
}
public static String translate(String element) {
return element + " " + Math.random();
}
Related
I have an array list of String element I want to duplicate last element of that list and that duplicate element set in the 0th position of same list. how to duplicate array list.
below is my input list:
List ["Apple","Tomato","Patato","Brinjal","Cabbage"]
I want below type of list as output:
List ["Cabbage","Apple","Tomato","Patato","Brinjal","Cabbage"]
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Apple");
cars.add("Tomato");
cars.add("Patato");
cars.add("Cabbage");
System.out.println(cars);
}
}
You can do something like this:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Apple");
cars.add("Tomato");
cars.add("Patato");
cars.add("Cabbage");
// Geting the last element of the list
String lastElement = cars.get(cars.size() - 1);
// Adding the last element to the starting of the list
cars.add(0, lastElement);
System.out.println(cars); // This should out put your expected result.
}
}
Since you specify needing a copy of the list, you might add the last element to an empty ArrayList<String> then use addAll to add the original list elements.
ArrayList<String> copiedArraylist = new ArrayList<String>();
copiedArraylist.add(cars.get(cars.size()-1);
copiedArraylist.addAll(1, cars);
Guys i wanna ask about the best way to iterate collection classes ??
private ArrayList<String> no = new ArrayList<String>();
private ArrayList<String> code = new ArrayList<String>();
private ArrayList<String> name = new ArrayList<String>();
private ArrayList<String> colour = new ArrayList<String>();
private ArrayList<String> size = new ArrayList<String>();
// method for finding specific value inside ArrayList, if match then delete that element
void deleteSomeRows(Collection<String> column, String valueToDelete) {
Iterator <String> iterator = column.iterator();
do{
if (iterator.next()==valueToDelete){
iterator.remove();
}
}while(iterator.hasNext());
}
deleteSomeRows(no, "value" );
deleteSomeRows(code, "value" );
deleteSomeRows(name , "value");
deleteSomeRows(colour ,"value" );
deleteSomeRows(size , "value");
THE PROBLEM WITH CODES ABOVE IS THAT IT TAKES AMOUNT OF TIME JUST TO ITERATE EACH OF THOSE CLASSES ? ANY SOLUTION TO MAKE IT FASTER ? pls help if u care :D..
You could simplify your code:
while column.contains(valueToDelete)
{
column.remove(valueToDelete);
}
You're not going to be able to speed up your ArrayList iteration, especially if your list is not sorted. You're stuck at O(n) for this problem. If you sorted it and inserted logic to binary search for the item to remove until it is no longer found, you could speed up access.
This next suggestion isn't directly related to the time it takes, but it will cause you problems.
You should never compare String objects for equality using the == operator. This will cause a comparison of their pointer values.
Use this instead:
if (iterator.next().equals(valueToDelete))
EDIT: The problem here is not the iteration. The problem is removing the elements from the ArrayList. When you remove the first element from an ArrayList, then all subsequent elements have to be shifted one position to the left. So in the worst case, your current approach will have quadratic complexity.
It's difficult to avoid this in general. But in this case, the best tradeoff between simplicity and performance can probably be achieved like this: Instead of removing the elements from the original list, you create a new list which only contains the elements that are not equal to the "valueToDelete".
This could, for example, look like this:
import java.util.ArrayList;
import java.util.List;
public class QuickListRemove
{
public static void main(String[] args)
{
List<String> size = new ArrayList<String>();
size = deleteAll(size, "value");
}
private static <T> List<T> deleteAll(List<T> list, T valueToDelete)
{
List<T> result = new ArrayList<T>(list.size());
for (T value : list)
{
if (!value.equals(valueToDelete))
{
result.add(value);
}
}
return result;
}
}
If you want to modify the collection while iterating them then you should use Iterators, otherwise you can use the for-each loop.
For -each :
// T is the type f elements stored in myList
for(T val : myList)
{
// do something
}
Try putting a break after you find the element to delete.
is it possible to run the following code with logic in 6th line ?
public class arraylist{
public static void main(String args{}){
String s[]={"Sam","Tom","Jerry"};
ArrayList al=new ArrayList();
al.add(s);//i want this type of logic so i can add the elements of string once.is it possible?
}
Iterator it=al1.iterator();
while(it.hasNext())
{
String element=String.valueOf(it.next());
System.out.print("Element"+element);
}
}
Change al.add(s); by al.addAll(Arrays.asList(s)); and you should be all set.
Try the following:
ArrayList<String> al = new ArrayList<String>(Arrays.asList(s));
You have the answer in your question.
When you say you want to convert array asList
As many have already suggested, use Arrays.asList. But before the code would work, you would still need to fix the formatting as you have code outside the main method that is referring to your array list variable in the main method.
public static void main(String[] args){
String s[]={"Sam","Tom","Jerry"};
ArrayList al=new ArrayList();
al.add(Arrays.asList(s));
Iterator it=al.iterator();
while(it.hasNext())
{
String element=String.valueOf(it.next());
System.out.print("Element"+element);
}
}
al.add(s);//i want this type of logic so i can add the elements of string once.is it possible ?
Yes. It is possible.You can add any object to ArrayList including array object.
But while iterating the ArrayList object you will get an array element by calling it.next().So output will be String representation of array object not the array elements
So try this
String s[]={"Sam","Tom","Jerry"};
ArrayList<String> al=Arrays.asList(s);
Iterator it=al.iterator();
while(it.hasNext())
{
String element=String.valueOf(it.next());
System.out.print("Element"+element);
}
I did the following to store arrays in a ArrayList. The declaration is:
ArrayList<String[]> training = new ArrayList<String[]>();
To input the words and add it:
String input = sc.nextLine();
s1 = input.split(" ");
training.add(s1);
The split method splits the string with spaces and stores each word in the respective index in array s1 which was already declared with the size required for the program."sc" is the scanner object already declared.The individual arrays can be accessed by using:
String s4[] = training.get(index_of_array_you_want);
Element[] array = {new Element(1), new Element(2), new Element(3)};
ArrayList arr=new ArrayList(Arrays.asList(array))
I'm trying to print all the elements of an arraylist and remove them from the array at the same time using the following code.
while(!duplicates.isEmpty()){
outpurWriter.println(duplicates.remove(0));
}
It works when the arraylist is small in size but if the arraylist contains say 400000 elements it crashes after the first few thousand.
I've changed my code around to just use a for loop to print each element then set the arraylist = null, but just wondering what is wrong with the code I used originally.
Cheers
Try this,
public static void main(String[] args)
{
List<String> listString = new ArrayList<String>();
listString.add("a");
listString.add("b");
listString.add("c");
listString.add("d");
System.out.println("Size of arraylist before remove: "+listString.size());
ListIterator<String> listIterator = listString.listIterator();
while (listIterator.hasNext())
{
listIterator.next();
listIterator.remove();
}
System.out.println("Size of arraylist after remove: "+listString.size());
}
If you have requirement where you have more insert and delete operations, please use linkedlist
I'm new to java (& to OOP too) and I'm trying to understand about the class ArrayList
but I don't understand how to use the get(). I tried searching in net, but couldn't find anything helpful.
Here is the official documentation of ArrayList.get().
Anyway it is very simple, for example
ArrayList list = new ArrayList();
list.add("1");
list.add("2");
list.add("3");
String str = (String) list.get(0); // here you get "1" in str
To put it nice and simply, get(int index) returns the element at the specified index.
So say we had an ArrayList of Strings:
List<String> names = new ArrayList<String>();
names.add("Arthur Dent");
names.add("Marvin");
names.add("Trillian");
names.add("Ford Prefect");
Which can be visualised as:
Where 0, 1, 2, and 3 denote the indexes of the ArrayList.
Say we wanted to retrieve one of the names we would do the following:
String name = names.get(1);
Which returns the name at the index of 1.
So if we were to print out the name System.out.println(name); the output would be Marvin - Although he might not be too happy with us disturbing him.
You use List#get(int index) to get an object with the index index in the list. You use it like that:
List<ExampleClass> list = new ArrayList<ExampleClass>();
list.add(new ExampleClass());
list.add(new ExampleClass());
list.add(new ExampleClass());
ExampleClass exampleObj = list.get(2); // will get the 3rd element in the list (index 2);
ArrayList get(int index) method is used for fetching an element from the list. We need to specify the index while calling get method and it returns the value present at the specified index.
public Element get(int index)
Example :
In below example we are getting few elements of an arraylist by using get method.
package beginnersbook.com;
import java.util.ArrayList;
public class GetMethodExample {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("pen");
al.add("pencil");
al.add("ink");
al.add("notebook");
al.add("book");
al.add("books");
al.add("paper");
al.add("white board");
System.out.println("First element of the ArrayList: "+al.get(0));
System.out.println("Third element of the ArrayList: "+al.get(2));
System.out.println("Sixth element of the ArrayList: "+al.get(5));
System.out.println("Fourth element of the ArrayList: "+al.get(3));
}
}
Output:
First element of the ArrayList: pen
Third element of the ArrayList: ink
Sixth element of the ArrayList: books
Fourth element of the ArrayList: notebook
Would this help?
final List<String> l = new ArrayList<String>();
for (int i = 0; i < 10; i++) l.add("Number " + i);
for (int i = 0; i < 10; i++) System.out.println(l.get(i));
The get() method returns an element. For example:
ArrayList<String> name = new ArrayList<String>();
name.add("katy");
name.add("chloe");
System.out.println("The first name in the list is " + name.get(0));
System.out.println("The second name in the list is " + name.get(1));
The output:
The first name in the list is katy
The second name in the list is chloe