I know it's simple question, but in
ArrayList<ArrayList<String>> collection;
ArrayList<String> listOfSomething;
collection= new ArrayList<ArrayList<String>>();
listOfSomething = new ArrayList<String>();
listOfSomething.Add("first");
listOfSomething.Add("second");
collection.Add(listOfSomething);
listOfSomething.Clear();
listOfSomething.Add("first");
collection.Add(listOfSomething);
I want to take String from ArrayList of ArrayList, and I don't know how to do that. For example I go
ArrayList<String> myList = collection.get(0);
String s = myList.get(0);
and it works! but:
Big update:
private List<S> valuesS;
private List<Z> valuesZ;
ArrayList<ArrayList<String>> listOfS;
ArrayList<String> listOfZ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Zdatasource = new ZDataSource(this);
Zdatasource.open();
valuesZ = Zdatasource.getAllZ();
Sdatasource = new SDataSource(this);
Sdatasource.open();
valuesS = Sdatasource.getAllS();
List<Map<String, String>> groupData
= new ArrayList<Map<String, String>>();
List<List<Map<String, String>>> childData
= new ArrayList<List<Map<String, String>>>();
listOfS = new ArrayList<ArrayList<String>>();
listOfZ = new ArrayList<String>();
for (S i : valuesS) { // S is class
for (Z j : valuesZ) { // Z is class
if(j.getNumerS().equals(i.getNumerS())) {
listOfZ.add(j.getNumerZ());
}
else
{
//listOfZ.add("nothing");
}
}
listOfS.add(listOfZ);
if(!listOf.isEmpty()) listOfZ.clear();
}
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
int childPosition, long id) {
try
{
ArrayList<String> myList = listOfS.get(groupPosition);
String s = myList.get(childPosition);
PrintToast("group "+Integer.toString(groupPosition)+", child "+Integer.toString(childPosition) + " , "+ s);
}
catch(Exception e)
{
Log.e("FS", e.toString());
}
return true;
}
return me java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0
when I click on item which really should exist. I didn't show code which generate ListView, but I can tell you that my listOfS contains 3 items:
first is Null listOfZ, second listOfZ got 2 elements, third listOfZ got 1 element.
listOfSomething.Clear();
listOfSomething.Add("first");
collection.Add(listOfSomething);
You are clearing the list here and adding one element ("first"), the 1st reference of listOfSomething is updated as well sonce both reference the same object, so when you access the second element myList.get(1) (which does not exist anymore) you get the null.
Notice both collection.Add(listOfSomething); save two references to the same arraylist object.
You need to create two different instances for two elements:
ArrayList<ArrayList<String>> collection = new ArrayList<ArrayList<String>>();
ArrayList<String> listOfSomething1 = new ArrayList<String>();
listOfSomething1.Add("first");
listOfSomething1.Add("second");
ArrayList<String> listOfSomething2 = new ArrayList<String>();
listOfSomething2.Add("first");
collection.Add(listOfSomething1);
collection.Add(listOfSomething2);
Because the second element is null after you clear the list.
Use:
String s = myList.get(0);
And remember, index 0 is the first element.
The right way to iterate on a list inside list is:
//iterate on the general list
for(int i = 0 ; i < collection.size() ; i++) {
ArrayList<String> currentList = collection.get(i);
//now iterate on the current list
for (int j = 0; j < currentList.size(); j++) {
String s = currentList.get(1);
}
}
A cleaner way of iterating the lists is:
// initialise the collection
collection = new ArrayList<ArrayList<String>>();
// iterate
for (ArrayList<String> innerList : collection) {
for (String string : innerList) {
// do stuff with string
}
}
I have String array like this
We have to pass data through response.body.getdata and this data pass in constructor like this,
List taginnerData;
"data": [
"banana",
"apple",
"grapes",
"Pears",
"Mango",
"Cherry",
"Guava",
"TorontoVsMilwaukee_12Jan19"
]
String[] myArray = new String[taginnerData.size()];
for (int i = 0; i < taginnerData.size(); i++) {
myArray[i] = String.valueOf(taginnerData.get(i));
holder.tv_channel_name.setText("" +taginnerData.get(i));
//we get any value from here to set in adapter
}
Related
I want to add object/data in an array after every 2nd element ....just for making more clear I am going to use a simple example
I have arrayList of :
List<Object> list = new ArrayList<>();
list.add("messi");
list.add("ronaldo");
list.add("rooney");
list.add("pogba");
list.add("hazard");
print(list);
//output : [messi, ronaldo, rooney, pogba,hazard]
What I want is:
//[messi, ronaldo, DATA, rooney, pogba, DATA, hazard]
how I can achieve this.
Adding data in an array after every 2nd element.
By maintaining a counter.
public class Main {
public static void main(String[] args) {
List<Object> list = new ArrayList<>();
list.add("messi");
list.add("ronaldo");
list.add("rooney");
list.add("pogba");
list.add("hazard");
int counter = 0 ;
List<Object> data = new ArrayList<>();
for(Object obj : list){
data.add(obj);
counter = counter + 1;
if(counter%2 == 0)
data.add("DATA");
}
for(Object obj : data)
System.out.println(obj);
}
}
So, you can do is create a new list to store the old data with new object:
List<Object> list = new ArrayList<>();
List<Object> newlist = new ArrayList<>();
list.add("messi");
list.add("ronaldo");
list.add("rooney");
list.add("pogba");
list.add("hazard");
for(int i = 0; i < list.size(); i++) {
if(i%2==0) {
// Add DATA after 2 items
newlist.add(data);
}
newlist.add(list.get(i));
}
Please someone format since I'm writing from my phone.
class sample {
public static void main(String[] args) {
List<Object> list = new ArrayList<>();
sample.addList("messi", list);
sample.addList("ronaldo", list);
sample.addList("rooney", list);
sample.addList("pogba", list);
sample.addList("hazard", list);
System.out.println(list);
}
private static void addList(String value, List<Object> objects) {
if (!objects.isEmpty() && (objects.size() % 3 == 2)) {
objects.add("Data");
}
objects.add(value);
}
}
You can create one utility method as mentioned above.
For every time before adding element check that if list.size() % 3 == 2 then add extra element.
This will help you.
Look at the desired output and the indexes of the inserted DATA values:
[messi, ronaldo, DATA, rooney, pogba, DATA, hazard]
0 1 2 3 4 5 6
The DATA values go in index 2, 5, 8, 11, ...
Which means it's a simple for loop calling add(int index, E element):
List<Object> list = new ArrayList<>();
list.add("messi");
list.add("ronaldo");
list.add("rooney");
list.add("pogba");
list.add("hazard");
System.out.println(list);
for (int i = 2; i < list.size(); i += 3) {
list.add(i, "DATA");
}
System.out.println(list);
Output
[messi, ronaldo, rooney, pogba, hazard]
[messi, ronaldo, DATA, rooney, pogba, DATA, hazard]
I am new to Android and Java and can't figure out this seemingly basic for loop setup to create an array of objects from the data in two other arrays.
It works this way, but this doesn't feel very sophisticated.
// RefineMenuItem is a public class
public class RefineMenuItem {
private int imageIcon;
private String title;
}
// imageIcon and title are arrays with seven values in them
int[] imageItems = { ... }
String[] menuItems = { ... }
// Create the RefineMenu Objects
RefineMenuItem item1 = new RefineMenuItem(imageItems[0],menuItems[0]);
RefineMenuItem item2 = new RefineMenuItem(imageItems[1],menuItems[1]);
RefineMenuItem item3 = new RefineMenuItem(imageItems[2],menuItems[2]);
RefineMenuItem item4 = new RefineMenuItem(imageItems[3],menuItems[3]);
RefineMenuItem item5 = new RefineMenuItem(imageItems[4],menuItems[4]);
RefineMenuItem item6 = new RefineMenuItem(imageItems[5],menuItems[5]);
RefineMenuItem item7 = new RefineMenuItem(imageItems[6],menuItems[6]);
// Add the RefineMenu Objects to an ArrayList
ArrayList<RefineMenuItem> refineMenuList = new ArrayList<>();
refineMenuList.add(item1);
refineMenuList.add(item2);
refineMenuList.add(item3);
refineMenuList.add(item4);
refineMenuList.add(item5);
refineMenuList.add(item6);
refineMenuList.add(item7);
I believe I need to create the array of objects first and then add to it based on this question.
RefineMenuItem[] arr = new RefineMenuItem[7];
Then I believe I should use a for loop to add to the array, but this is where I'm getting stuck and can't figure it out after researching. Help to point me in the right direction is appreciated!
A basic for loop could solve all your problems I believe.
Just make sure you make your implementations/declarations before.
for(int i = 0; i<=6; i++) {
RefineMenuItem item = new RefineMenuItem(imageItems[i],menuItems[i]);
refineMenuList.add(item);
}
I'm gonna be brutally honest, haven't worked with java in a while so there might be some syntax errors but the logical solution should be supplemental.
It is impossible to create an ArraysList directly from two arrays. You first, need to create an array of the RefineMenuItem objects and add them. However, instead of creating a new array just to add all at once, create them as soon as you instantiate them... Like:
int size;
if(imageItems != null && menuItems != null && menuItems.length == imageItems.length) {
size = menuItems.length;
} else {
size = 0;
}
ArrayList<RefineMenuItem> refineMenuList = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
refineMenuList.add(new RefineMenuItem(imageItems[i],menuItems[i]));
}
A precondition is that imageItems and menuItems have the same number of elements in them. So I'd start by asserting that.
Then you can create a new array of the same size, and use a for loop to iterate:
int[] imageItems = { ... }
String[] menuItems = { ... }
if (imageItems.length != menuItems.length) {
throw new IllegalStateException("array lengths don't match");
}
RefineMenuItem[] result = new RefineMenuItem[imageItems.length];
for (int i = 0; i < imageItems.length; ++i) {
result[i] = new RefineMenuItem(imageItems[i], menuItems[i]);
}
When this code completes, the result array will be fully populated.
// RefineMenuItem is a public class
public class RefineMenuItem {
private int imageIcon;
private String title;
}
// imageIcon and title are arrays with seven values in them
int[] imageItems = { ... }
String[] menuItems = { ... }
// create array list
ArrayList<RefineMenuItem> refineMenuList = new ArrayList<>();
// add items to the array list in a for loop
for (int i = 0; i < imageItems.length; i++) {
refineMenuList.add(new RefineMenuItem(imageItems[i], menuItems[i]));
}
This is assuming the imageItems and menuItems are always the same length
The premise of this is you can create the ArrayList and then use a for loop to iterate over your imageItems and menuItems, create a new RefineMenuItem from them, and add it to the refineMenuList
you should be adding it to a class array this way:
import java.util.ArrayList.add
RefineMenuItem[] items = new RefineMenuItem();
for(int i=0 ; i<7 ; i++ ){
RefineMenuItem thing = new RefineMenuItem(RefineMenuItem(imageItems[i],menuItems[i])
items[i].add(i,thing))
}
I got a problem when insert an ArrayList into ArrayList.
My source code:
import java.util.ArrayList;
public class Ask {
public static void main(String[] args) {
ArrayList<String> mentah = new ArrayList<String>();
mentah.add("Reza");
mentah.add("Fata");
mentah.add("Faldy");
mentah.add("Helsan");
mentah.add("Dimas");
mentah.add("Mamun");
mentah.add("Erik");
mentah.add("Babeh");
mentah.add("Tio");
mentah.add("Mamang");
ArrayList<ArrayList<String>> result =new ArrayList<ArrayList<String>>();
result.add(mentah);
}
}
How can I create a list based on that data; that will look like:
[[data1,data2,data3],[data4,data5,data6],[data7,data8,data9,data10]]
10 div 3 is 3 (so 3 elements per sublist)
10 mod 3 is 1 (so last sublist has 4 entries)
10 divide by 3 is
3 3 4
Just upgraded the answer of #Narayana Ganesh:
ArrayList<String> mentah = new ArrayList<String>();
mentah.add("Reza");
mentah.add("Fata");
mentah.add("Faldy");
mentah.add("Helsan");
mentah.add("Dimas");
mentah.add("Mamun");
mentah.add("Erik");
mentah.add("Babeh");
mentah.add("Tio");
mentah.add("Mamang");
List<List<String>> result = new ArrayList<List<String>>();
for (int j= 0; j< mentah.size() ; j+=3) {
int end = mentah.size() <= j+2 ? mentah.size() : j+3;
if(mentah.size() - j == 4) end = end +1;
if(j != 9) result.add(mentah.subList(j, end));
}
System.out.println(result);
}
Result:
[[Reza, Fata, Faldy], [Helsan, Dimas, Mamun], [Erik, Babeh, Tio, Mamang]]
A more generic solution would look like:
List<String> allNames = Arrays.asList("Reza", "Fata", ...
List<List<String>> slicedNames = new ArrayList<>();
List<String> sublist = new ArrayList<>();
int sublistTargetLength = 3;
for (String name : allNames) {
sublist.add(name);
if (sublist.size() == sublistTargetLength) {
slicedNames.add(sublist);
sublist = new ArrayList<>();
}
}
if (sublist.size() > 0) {
slicedNames.get(slicedNames.size()-1).addAll(sublist);
}
Some notes:
The above iterates your initial list of names (which can created using that single call to Arrays.asList()); and puts the entries into same-sized lists; which are then added to the slicedNames list of list.
If there is any "remaining" data; that is simply added to the last element of the list of list.
You should prefer to use the interface type List for your variable types; you only use the specific implementation class (ArrayList) when instantiating the list
When iterating anything, prefer the for-each looping style when possible
Try this. You can achieve this using subList method.
import java.util.ArrayList;
import java.util.List;
public class Ask {
public static void main(String[] args) {
ArrayList<String> mentah = new ArrayList<String>();
mentah.add("Reza");
mentah.add("Fata");
mentah.add("Faldy");
mentah.add("Helsan");
mentah.add("Dimas");
mentah.add("Mamun");
mentah.add("Erik");
mentah.add("Babeh");
mentah.add("Tio");
mentah.add("Mamang");
List<List<String>> result = new ArrayList<List<String>>();
for (int j= 0; j< mentah.size() ; j+=3) {
int end = mentah.size() <= j+2 ? mentah.size() : j+3;
result.add(mentah.subList(j, end));
}
for (List<String> item : result) {
System.out.println(" - -"+item);
}
}
}
First create sublists with a maximal size of 3 which will give you something like this
[[Reza, Fata, Faldy], [Helsan, Dimas, Mamun], [Erik, Babeh, Tio], [Mamang]]
then check if the last sublist size is less than 3 if yes add this to the second last sublist and remove the last one
public class Example {
public static void main(String[] args) {
List<String> mentah = new ArrayList<>();
mentah.add("Reza");
mentah.add("Fata");
mentah.add("Faldy");
mentah.add("Helsan");
mentah.add("Dimas");
mentah.add("Mamun");
mentah.add("Erik");
mentah.add("Babeh");
mentah.add("Tio");
mentah.add("Mamang");
List<List<String>> parts = new ArrayList<>();
int sizeOfOriginalList = mentah.size();
int sizeOfSubLists = 3;
for (int i = 0; i < sizeOfOriginalList; i += sizeOfSubLists) {
parts.add(new ArrayList<>(mentah.subList(i, Math.min(sizeOfOriginalList, i + sizeOfSubLists))));
}
if(parts.get(parts.size()-1).size()<sizeOfSubLists){
parts.get(parts.size()-2).addAll(parts.get(parts.size()-1));
parts.remove(parts.get(parts.size()-1));
}
System.out.println(parts);
}
}
When I acces to list of list with this function,It make ConcurrentModificationException in second for loop but i don't understand why this Exception is triggered .
public static List<List<Dico>> weight_term(List<List<Dico>> sublists ,List<String> sinificativ )
{
List<List<Dico>> matrix_node_term = new ArrayList<>();
List<Dico> list_node = new ArrayList<>();// a new list for node
for (List<Dico> sublist : sublists) // to get each sublist List<Dico>
{
for (Dico dico : sublist) // get each Dico in the sublist -->ConcurrentModificationException
{
String term =dico.getTerm();
int id = dico.getDocId();
if(sinificativ.contains(term)) // if this term exist in sinificativ erm list
{
list_node.add(dico); // it add to list_node
}
else
{
list_node.add(new Dico(id,term,0.0)); // it add to list_node with null weigth
}
}
matrix_node_term.add(list_node); // add each list to list of list
}
return matrix_node_term;
}
The dico class is used to store term,id of document and the weight of this term in that document :
public class Dico implements Comparable
{
private final String m_term;
private double m_weight;
private final int m_Id_doc;
public Dico(int Id_Doc,String Term,double tf_ief )
{
this.m_Id_doc = Id_Doc;
this.m_term = Term;
this.m_weight = tf_ief;
}
}
This Exception is triggered without any modification in the sutucte of list or its elements .
Probleme comes from a function used to split List in multiple List:
List<List<Dico>> sublists = new ArrayList<>(change);
for (int i = 0; i < change; i++)
{
sublists.add(list.subList(changes[i],changes[i + 1]));
}
A solution comes from pbabcdefp
List<List<Dico>> sublists = new ArrayList<>(change);
for (int i = 0; i < change; i++)
{
sublists.add(newArrayList<Dico>(list.subList(changes[i], changes[i + 1])));
}
thank you for your help
I have something in my mind which have been bothering me for quite a while now and hope I can get some kind souls to help... :D
Anyway, here's what I wanna do:
I do actually have a number of list, say
List<String> a = {"for testA1", "for testA2", "for testA3"};
List<String> b; = {"for testB1", "for testB2", "for testB3"};
List<String> c; = {"for testC1", "for testC2", "for testC3"};
And I have an array list of objects that I want to add these strings into, i.e.
List<ObjectA> thislist = new ArrayList<ObjectA>();
In my ObjectA class I have:
public class ObjectA{
String testA;
String testB;
String testC;
}
My final output should be:
List<ObjectA> -
testA1
testB1
testC1
testA2
testB2
testC2
testA3
testB3
testC3
How can I go about setting these Strings in my object from the given individual list?
Sorry for my bad English, I hope it's understandable.
I had this in mind but didn't quite understand.
My code was
List<String> aList = ....;
List<String> bList = ....;
List<String> cList = ....;
List<ObjectA> someList = new ArrayList<ObjectA>();
for(String a: aList){
ObjectA obj = new ObjectA();
obj.setTestA(a);
}
ListIterator litr = someList.listIterator();
while(litr.hasNext()) {
ObjectA element = (ObjectA) litr.next();
// I wanna loop List<String> bList and add element.setTestB but it doesn't work.
// This is what I wanna do...
}
Iterator<String> aIt = a.iterator();
Iterator<String> bIt = b.iterator();
Iterator<String> cIt = c.iterator();
List<ObjectA> thislist = new ArrayList<ObjectA>();
// assumes all the lists have the same size
while(aIt.hasNext())
{
Object A o = new ObjectA(aIt.next(), bIt.next(), cIt.next());
thisList.add(o);
}
// do all the assertions to check that the sizes are the same
if (a.size() != b.size() || a.size() != c.size()) {
throw new IllegalStatException("Wrong size");
}
List<ObjectA> objects = new ArrayList<ObjectA>();
for (int i = 0; i < a.size(); i++) {
String aStr = a.get(i);
String bStr = b.get(i);
String cStr = c.get(i);
ObjectA obj = new ObjectA(aStr, bStr, cStr);
objects.add(obj);
}
Comment below makes a good point - this could potentially be an O(n^2) solution in the case of a linked list (or any other list which has O(n) access time to access arbitrary elements)
Well, assuming you mapped object is of type
public class Triplet{
private final String jedi;
private final String sith;
private final String padawan;
public Triplet(String jedi, String sith, String padawan){
this.jedi = jedi;
this.sith = sith;
this.padawan = padawan;
}
}
We could define a mapping iterator:
public static class TripletIterator implements Iterator<Triplet>{
Iterator<String> jedis;
Iterator<String> siths;
Iterator<String> padawans;
public TripletIterator(List<String> jedis, List<String> sith, List<String> padawns){
this.jedis = jedis.iterator();
this.siths = sith.iterator();
this.padawans = padawns.iterator();
}
#Override
public boolean hasNext() {
return jedis.hasNext() && siths.hasNext() && padawans.hasNext();
}
#Override
public Triplet next() {
return new Triplet(jedis.next(), siths.next(), padawans.next());
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
}
Then you could simply:
List<String> jedis = asList("Obiwan","Yoda","Luke");
List<String> siths = asList("Lord Sidious", "Darth Mul", "Darth Vader");
List<String> padawans = asList("Anakin", "Jarjar", "Poncho");
Iterator<Triplet> iter = new TripletIterator(jedis, siths, padawans);
while(iter.hasNext()){
Triplet t = iter.next();
System.out.println(t);
}
for(int i = 0; i < 3; i++) {
ObjectA oa = new ObjectA();
oa.testA = a[i];
oa.testB = b[i];
oa.testC = c[i];
thislist.Add(oa);
}