I have a question about setting the value to the list of strings in Java.
For example, if you have a list of strings called names, how would you set the 3rd name to the value "San Diego"?
I tried names.add(2, "San Diego") but it's not working.
Thanks so much for the help!
To update the already existing value use names.set(2,"String");
names.add(2, "San Diego") will add a new element at the 3rd position (index 2), but it will only work if the List already contains at least 2 elements.
names.set(2, "San Diego") will set the 3rd element (at index 2) to the required value, but it will work only if the List already contains at least 3 elements.
To obtain the 3rd element, you should use names.get(2) (again, the List must contain at least 3 elements for this to work).
If you want to replace an existing item in a list, you have to use set instead of add
names.set(2,"San Diego");
In here 2 means the index, counting from 0.
Then is the String you want to add
If you want to read values from the list you can use get
String value = names.get(2);
it will work if the List already contains at least 2 elements.
names.add(2, "San Diego") it will override the 3rd element or at index 2.
it is always safe to use
names.set(2, "San Diego") it will set the 3rd value or at index 2 if the list contains at least 3 elements.
Otherwise, it will throw IndexOutOfBoundsException: exception.
Here are the basic operation you can perform there are plenty of operation you can perform.
One advice try try and try dont give up.
here the is link for java dock for your reference
Java doc for List
package com.varun.list;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ArrayListTest {
public static void main(String[] args) {
//Create array list
List < String > names = new ArrayList < String > ();
//Create few names
String sam = "Sam";
String jamie = "Jamie_dogLover";
String bucy = "The Bucky";
// add all names in the list
names.add(sam);
names.add(jamie);
names.add(bucy);
System.out.println("List values :" + names); //Output : List values :[Sam, Jamie_dogLover, The Bucky]
//Update the second index that is -> The Bucky, because list index starts from 0
names.set(2, "New Bucky");
System.out.println("New List values :" + names); //Output : New List values :[Sam, Jamie_dogLover, New Bucky]
//Lest say you want to remove the the 1st index that is jamie
names.remove(jamie);
System.out.println("Updates List values :" + names); //Output : Updates List values :[Sam, New Bucky]
//Let say you get a list of name from somewhere and you want to add into you existing list(names)
names.addAll(listOfDummyNames());
System.out.println("Updates List values with dummy names :" + names);
//Output : Updates List values with dummy names :[Sam, New Bucky, Name0, Name1, Name2, Name3, Name4]
//Let say you want to to remove all the name who has "name" String in it
Iterator < String > itr = names.iterator();
while (itr.hasNext()) {
String name = itr.next();
if (name.contains("Name")) {
itr.remove();
}
}
System.out.println("List after removing all name who has Name in it : " + names);
}
private static List < String > listOfDummyNames() {
List < String > dummyList = new ArrayList < String > ();
String name = "Name";
for (int i = 0; i < 5; i++) {
dummyList.add(name + i);
}
System.out.println("List of dummy Names :" + dummyList);
return dummyList;
}
}
Related
I have the below three elements :
play_full_NAME=556677
pause_full_NAME=9922
stop_full_NAME=112233
A string "abc" returns all the above three elements one by one from a particular piece of code.
I am trying to add all three elements in a list separated by a colon ":"
Sample output :
play_full_NAME=556677:pause_full_NAME=9922:stop_full_NAME=112233
My attempt:
List<String> list = new ArrayList<String>();
list.join(":",abc)
Please help with a better way to handle this.
Your understanding about List is little flawed. Comma is only printed for representation purposes.
To join strings with colon, you can do the following
List<String> list = Arrays.asList("play_full_NAME=556677",
"pause_full_NAME=9922",
"stop_full_NAME=112233");
String joinedString = String.join(":", list);
Did you really understood the List well?
In fact, there is no separator, each item / value is stored as different "object".
So you have some amount of independent values- Strings in this case, what can you see on screenshot bellow, or if you will do System.out.println(someList); it will call override of method toString() which is inherited from Object class , which is root parent class of all classes in Java.
So its absolutely nonsense to add some split character between each items in List, they are split already, you can access each item by get(int position) method.
So if you want to print each item of list "by yourself", can be done like follows:
for (int i = 0; i < someList.size(); i++) {
System.out.println(i + " = " + someList.get(i));
}
/* output will be
1 = 1 item
2 = 2 item
3 = 3 item
4 = 4 item
*/
If you want to implement custom method for printing "your list" then you can extend eg. ArrayList class and override toString method, but better and more trivial approach will be prepare some method in some utils to get formatted String output with context of List- eg. (notice there will be ; after last element)
public static String getFormatStringFromList(ArrayList<String> data) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < data.size(); i++) {
sb.append(data.get(i) + ";");
}
return sb.toString();
//eg. 0 item;1 item;2 item;3 item;4 item;
}
To avoid last separator you can do eg. simple check
public static String getFormatStringFromListWitoutLastSeparator(List<String> someList) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < someList.size(); i++) {
sb.append(someList.get(i));
if(i < someList.size() -1) {
sb.append(";");
}
}
return sb.toString();
//0 item;1 item;2 item;3 item;4 item
/*
someList[0] = 0 item
someList[1] = ;
someList[2] = 1 item
someList[3] = ;
{etc..}
*/
}
The best approach to get String from list will be like #krisnik advised:
String joinedString = String.join(":", list);
You would need to add the colon elements separately if you want them to be within your list.
For example:
List<String> list = new ArrayList<String>();
list.add(abc);
list.add(":");
list.add(def);
list.add(":");
and so on.
I would recommend against this, however, as you can simply format the output string using String.format or a StringBuilder when you need it.
I have a List of Strings, and most of them are multiple words:
"how are you"
"what time is it"
I want to remove the space from every string in this list:
"howareyou"
"whattimeisit"
I know of the Collections.replaceAll(list, to replace, replace with), but that only applies to Strings that are that exact value, not every instance in every String.
What you must is to apply the replace function to each of the string in your list.
And as the strings are immutable you will have to create another list where string with no space will be stored.
List<String> result = new ArrayList<>();
for (String s : source) {
result.add(s.replaceAll("\\s+", ""));
}
Immutable means that object can not be changed, it must be created new one if you want to change the state of it.
String s = "how are you";
s = s.replaceAll("\\s+", "");
The function replaceAll returns the new string if you did not assign it to variable s then would still have spaces.
It doesn't sound very useful.
But try this:
import java.util.Arrays;
import java.util.List;
/**
* http://stackoverflow.com/questions/20760578/how-do-i-replace-characters-in-every-string-in-my-list-in-java/20760659#20760659
* Date: 12/24/13
* Time: 7:08 AM
*/
public class SpaceEater {
public static void main(String[] args) {
List<String> stringList = Arrays.asList(args);
System.out.println("before: " + stringList);
for (int i = 0; i < stringList.size(); ++i) {
stringList.set(i, stringList.get(i).replaceAll("\\s+", ""));
}
System.out.println("after : " + stringList);
}
}
disrvptor was correct - original snippet did not alter the list. This one does.
You can try this:
No need to define new array list. Use list.set this set replaces the element at the specified position in this list with the specified element.
int i = 0;
for (String str : list)
{
list.set(i, str.replaceAll(" ", ""));
i++;
}
Output
for (String s : list)
{
System.out.println(s);
}
//Thisisastring
//Thisisanotherstring
The only way I know how to do this is to iterate over the list, perform the replace operation on every object and replace the original object with the new one. This is best handled with 2 lists (source and target).
I am fairly new to Java and I have stumbled across a problem I cannot figure out for the life of me. First let me explain what I am trying to do then I will show you the code I have so far.
I have a webservice that returns an array of arrays(which include company and lines of business strings). I wish to transform this into a string list, which I did in the first line of code below. Then I wish to Iterate through the list and every I come across a different value for company, I want to create a new ArrayList and add the associated line of business to the new list. Example output of webservice: 80,80,64,64 (this is presorted so the same companies will always be grouped together) the associated lobs would be 1,2,3,4 respectively. What I want: arraylist[0]: 1,2 arrayList[1]: 3,4
What I have so far:
List coList = Arrays.asList(coArray);
//create list of lists
List<List<String>> listOfLists = new ArrayList<List<String>>();
String cmp = "";
for (int i=0;i<coList.size();i++){//loop over coList and find diff in companies
String currentCo = ((__LOBList)coList.get(i)).getCompany();
String currentLob = ((__LOBList)coList.get(i)).getLobNum();
if(i<coArray.length-1){
String nextCo = ((__LOBList)coList.get(i+1)).getCompany();
if((currentCo.equals(nextCo))){
//do nothing companies are equal
}else{
log("NOT EQUAL"); //insert logic to create a new array??
ArrayList<String> newList = new ArrayList<String>();
// for(int j=0;j<coList.size();j++){
newList.add( ((__LOBList)coList.get(i)).getLobNum());
// }
for(int k=0; k<listOfLists.size();k++){//loop over all lists
for(int l=0;l<listOfLists.get(k).size();l++){ //get first list and loop through
}
listOfLists.add(newList);
}
}
}
}
My problem here is that it is not adding the elements to the new string array. It does correctly loop through coList and I put a log where the companies are not equal so I do know where I need to create a new arrayList but I cannot get it to work for the life of me, please help!
Yes you can do this but it's really annoying to write in Java. Note: This is a brain dead simple in a functional programming language like Clojure or Haskell. It's simply a function called group-by. In java, here's how I'd do this:
Initialize a List of Lists.
Create a last pointer that is a List. This holds the last list you've added to.
Iterate the raw data and populate into the last as long as "nothing's changed". If something has changed, create a new last.
I'll show you how:
package com.sandbox;
import java.util.ArrayList;
import java.util.List;
public class Sandbox {
public static void main(String[] args) {
ArrayList<String> rawInput = new ArrayList<String>();
rawInput.add("80");
rawInput.add("80");
rawInput.add("60");
rawInput.add("60");
new Sandbox().groupBy(rawInput);
}
public void groupBy(List<String> rawInput) {
List<List<String>> output = new ArrayList<>();
List<String> last = null;
for (String field : rawInput) {
if (last == null || !last.get(0).equals(field)) {
last = new ArrayList<String>();
last.add(field);
output.add(last);
} else {
last.add(field);
}
}
for (List<String> strings : output) {
System.out.println(strings);
}
}
}
This outputs:
[80, 80]
[60, 60]
Of course, you can do what the other guys are suggesting but this changes your data type. They're suggesting "the right tool for the job", but they're not mentioning guava's Multimap. This will make your life way easier if you decide to change your data type to a map.
Here's an example of how to use it from this article:
public class MutliMapTest {
public static void main(String... args) {
Multimap<String, String> myMultimap = ArrayListMultimap.create();
// Adding some key/value
myMultimap.put("Fruits", "Bannana");
myMultimap.put("Fruits", "Apple");
myMultimap.put("Fruits", "Pear");
myMultimap.put("Vegetables", "Carrot");
// Getting the size
int size = myMultimap.size();
System.out.println(size); // 4
// Getting values
Collection<string> fruits = myMultimap.get("Fruits");
System.out.println(fruits); // [Bannana, Apple, Pear]
Collection<string> vegetables = myMultimap.get("Vegetables");
System.out.println(vegetables); // [Carrot]
// Iterating over entire Mutlimap
for(String value : myMultimap.values()) {
System.out.println(value);
}
// Removing a single value
myMultimap.remove("Fruits","Pear");
System.out.println(myMultimap.get("Fruits")); // [Bannana, Pear]
// Remove all values for a key
myMultimap.removeAll("Fruits");
System.out.println(myMultimap.get("Fruits")); // [] (Empty Collection!)
}
}
It sounds to me like a better choice would be a Map of Lists. Let the company ID be the key in the Map and append each new item for that company ID to the List that's the value.
Use the right tool for the job. Arrays are too low level.
Create a Map<String, List<Bussiness>>
Each time you retrieve a company name, first check if the key is already in the map. If it is, retrieve the list and add the Bussiness object to it. If it is not, insert the new value when a empty List and insert the value being evaluated.
try to use foreach instead of for
just like
foreach(List firstGroup in listOfLists)
foreach(String s in firstGroup)
............
Thanks for the input everyone!
I ended up going with a list of lists:
import java.util.*;
import search.LOBList;
public class arraySearch {
/**
* #param args
*/
public static void main(String[] args) {
LOBList test = new LOBList();
test.setCompany("80");
test.setLOB("106");
LOBList test1 = new LOBList();
test1.setCompany("80");
test1.setLOB("601");
LOBList test2 = new LOBList();
test2.setCompany("80");
test2.setLOB("602");
LOBList test3 = new LOBList();
test3.setCompany("90");
test3.setLOB("102");
LOBList test4 = new LOBList();
test4.setCompany("90");
test4.setLOB("102");
LOBList test5 = new LOBList();
test5.setCompany("100");
test5.setLOB("102");
LOBList BREAK = new LOBList();
BREAK.setCompany("BREAK");
BREAK.setLOB("BREAK");
BREAK.setcompany_lob("BREAK");
// create arraylist
ArrayList<LOBList> arlst=new ArrayList<LOBList>();
// populate the list
arlst.add(0,test);
arlst.add(1,test1);
arlst.add(2,test2);
arlst.add(3,test3);
arlst.add(4,test4);
arlst.add(5,test5);
//declare variables
int idx = 0;
String nextVal = "";
//loops through list returned from service, inserts 'BREAK' between different groups of companies
for(idx=0;idx<arlst.size();idx++){
String current = arlst.get(idx).getCompany();
if(idx != arlst.size()-1){
String next = arlst.get(idx+1).getCompany();
nextVal = next;
if(!(current.equals(next))){
arlst.add(idx+1,BREAK);
idx++;
}
}
}
//add last break at end of arrayList
arlst.add(arlst.size(),BREAK);
for(int i=0;i<arlst.size();i++){
System.out.println("co:" + arlst.get(i).getCompany());
}
//master array list
ArrayList<ArrayList<LOBList>> mymasterList=new ArrayList<ArrayList<LOBList>>();
mymasterList = searchListCreateNewLists(arlst);
//print log, prints all elements in all arrays
for(int i=0;i<mymasterList.size();i++){
for(int j=0;j<mymasterList.get(i).size();j++){
System.out.println("search method: " + mymasterList.get(i).get(j).getCompany());
}
System.out.println("end of current list");
}
}
//method to loop over company array, finds break, creates new array list for each company group,
//adds this to a list of lists(masterList)
public static ArrayList<ArrayList<LOBList>> searchListCreateNewLists(ArrayList<LOBList> list){
ArrayList<ArrayList<LOBList>> masterList=new ArrayList<ArrayList<LOBList>>();
int end = 0;
int start = 0;
int index = 0;
for(int i=0;i<list.size();i++){
if(list.get(i).getCompany().equals("BREAK")){
end = i;//end is current index
masterList.add(new ArrayList<LOBList>());
for(int j = start;j<end;j++){
masterList.get(index).add(list.get(j));
}
index++;
start = i+1;
}
}
return masterList;
}
}
The output is:
search method: 80
search method: 80
search method: 80
end of current list
search method: 90
search method: 90
end of current list
search method: 100
end of current list
So all company LOBList objects with Company: 80, are grouped together in a list, as are 90 and 100.
To iterate through the list you can use
ListIterator litr = coList.listIterator();
while(litr.hasNext()){
}
I have an ArrayList(String) which contains a list of formatted dates like this:
element 1: "2012-5-1"
element 2: "2012-8-10"
element 3: "2012-12-5"
element 4: "2013-12-21"
element 5: "2013-12-13"
element 6: "2014-5-8"
What is the most efficient/framework way to create another list or normal primitive array that contains the unique year entries? For example my new list would contain:
element 1: "2012"
element 2: "2013"
element 3: "2014"
Try this
ArrayList<String> yearsOnlylist = new ArrayList<String> ();
for(String s : elements) {
String yearExtracted = s.substring(0,4);
yearsOnlylist.add(yearExtracted);
}
Where elements is the name of your list of date in the extended form.
Using as destination list
LinkedList<String> yearsOnlylist = new LinkedList<String> ();
instead of an ArrayList could sightly improve the conversion efficiency (because the add is O(1) in LinkedList) but access a specific position in a second time, has a lower efficiency (O(n) vs O(1)).
Just add them to a Set and convert it to a list:
Set<String> unique = new HashSet<String>();
for (String element : elements) {
set.put(element.substring(0,4));
}
List<String> uniqueList = new ArrayList<String>();
uniqueList.addAll(unique);
Iterate through your array list and take a substring of the first 4 characters of each member of the array list.
Add that substring to a set implementation such as a HashSet, which will give you what you want.
public List<String> trimmer(List<String> x) {
Log.e("", Integer.toString(x.size()));
for (int i = 0; i < x.size(); i++) {
String s = x.get(i).toString();
String a = s.substring(6);
Log.e("after trim is?", a);
x.remove(i);
x.add(i, a);
}
// check if the element got added back
Log.e("Trimmer function", x.get(1));
return x;
}
This will help you hopefully!
Say I have a List like:
List<String> list = new ArrayList<>();
list.add("a");
list.add("h");
list.add("f");
list.add("s");
While iterating through this list I want to add an element at the end of the list. But I don't want to iterate through the newly added elements that is I want to iterate up to the initial size of the list.
for (String s : list)
/* Here I want to add new element if needed while iterating */
Can anybody suggest me how can I do this?
You can't use a foreach statement for that. The foreach is using internally an iterator:
The iterators returned by this class's iterator and listIterator
methods are fail-fast: if the list is structurally modified at any
time after the iterator is created, in any way except through the
iterator's own remove or add methods, the iterator will throw a
ConcurrentModificationException.
(From ArrayList javadoc)
In the foreach statement you don't have access to the iterator's add method and in any case that's still not the type of add that you want because it does not append at the end. You'll need to traverse the list manually:
int listSize = list.size();
for(int i = 0; i < listSize; ++i)
list.add("whatever");
Note that this is only efficient for Lists that allow random access. You can check for this feature by checking whether the list implements the RandomAccess marker interface. An ArrayList has random access. A linked list does not.
Iterate through a copy of the list and add new elements to the original list.
for (String s : new ArrayList<String>(list))
{
list.add("u");
}
See
How to make a copy of ArrayList object which is type of List?
Just iterate the old-fashion way, because you need explicit index handling:
List myList = ...
...
int length = myList.size();
for(int i = 0; i < length; i++) {
String s = myList.get(i);
// add items here, if you want to
}
You could iterate on a copy (clone) of your original list:
List<String> copy = new ArrayList<String>(list);
for (String s : copy) {
// And if you have to add an element to the list, add it to the original one:
list.add("some element");
}
Note that it is not even possible to add a new element to a list while iterating on it, because it will result in a ConcurrentModificationException.
I do this by adding the elements to an new, empty tmp List, then adding the tmp list to the original list using addAll(). This prevents unnecessarily copying a large source list.
Imagine what happens when the OP's original list has a few million items in it; for a while you'll suck down twice the memory.
In addition to conserving resources, this technique also prevents us from having to resort to 80s-style for loops and using what are effectively array indexes which could be unattractive in some cases.
To help with this I created a function to make this more easy to achieve it.
public static <T> void forEachCurrent(List<T> list, Consumer<T> action) {
final int size = list.size();
for (int i = 0; i < size; i++) {
action.accept(list.get(i));
}
}
Example
List<String> l = new ArrayList<>();
l.add("1");
l.add("2");
l.add("3");
forEachCurrent(l, e -> {
l.add(e + "A");
l.add(e + "B");
l.add(e + "C");
});
l.forEach(System.out::println);
We can store the integer value while iterating in the list using for loop.
import java.util.*;
class ArrayListDemo{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
List<Integer> list = new ArrayList<Integer>();
System.out.println("Enter the number of elements you wanna print :");
int n = scanner.nextInt();
System.out.println("Enter the elements :");
for(int i = 0; i < n; i++){
list.add(scanner.nextInt());
}
System.out.println("List's elements are : " + list);
/*Like this you can store string while iterating in java using forloop*/
List<String> list1 = new ArrayList<String>();
System.out.println("Enter the number of elements you wanna store or print : ");
int nString = scanner.nextInt();
System.out.println("Enter the elements : ");
for(int i = 0; i < nString; i++){
list1.add(scanner.next());
}
System.out.println("Names are : " + list1);
scanner.close();
}
}
Output:
Enter the number of elements you wanna print :
5
Enter the elements :
11
12
13
14
15
List's elements are : [11, 12, 13, 14, 15]
Enter the number of elements you wanna store or print :
5
Enter the elements :
apple
banana
mango
papaya
orange
Names are : [apple, banana, mango, papaya, orange]