I am having a resultList which is a string list were each element in this list is also a List<String>. Now I want to put my data into a csv sheet. For that I am using opencsv.
List<String[]> data = new ArrayList<String[]>();
for(int m = 0; m < resultList.get(0).size(); m++) {
for (int i = 0; i < resultList.size(); i++) {
data.add(new String[] {resultList.get(i).get(m).toString()});
}
}
writer.writeAll(data);
//close Writer
writer.close();
My data should look like that:
However, my implementation gives me that:
In my implementation I am taking, knowing that every sublist has the same length, from each sublist the first element and add it to the array. Why am I getting this long row?
I appreciate your replies!
Because your loop is incorrect. You constructed a new String array in every inner loop, so every array has only on element.
Try the following code:
List<String[]> data = new ArrayList<String[]>();
for(List<String> strlist : resultList) {
String[] array = new String[strlist.size()];
int offset = 0;
for(String s : strlist) {
array[offset ++] = s;
}
data.add(array);
}
============== Edited bellow ==================
I've re-ordered the loop to match your output requirement. Also, a sample input is provided to test the algorithm.
List<List<String>> resultList = new ArrayList<List<String>>();
for (int i = 1; i <= 9; i++) {
List<String> innerList = new ArrayList<String>();
resultList.add(innerList);
for (int j = 1; j <= 9; j++) {
innerList.add(j + "");
}
}
List<String[]> data = new ArrayList<String[]>();
for(int m = 0; m < resultList.get(0).size(); m++) {
String[] array = new String[resultList.size()];
for (int i = 0; i < resultList.size(); i++) {
array[i] = resultList.get(i).get(m).toString();
}
data.add(array);
}
for(String[] array : data) {
System.out.println(Arrays.toString(array));
}
Related
I am creating an ArrayList of String Arrays in Java.. The code for the same is follows..
ArrayList<String[]> al = new ArrayList<String[]>();
for(int i = 0; i < t; i++) { // t is input by user representing size of arraylist
int k = sc.nextInt();
String[] s = new String[k]; // k string values input by user
}
Iterating to print the values of ArrayList
Iterator it = al.iterator();
while(it.hasNext()){
for(int i = 0; i < (it.next(new String[])).length; i++) { // error for dimension missing
System.out.println((it.next(new String[])).length); // error for dimension missing
}
}
I get an error of "array dimension missing" in the indicated lines. Please suggest how to convert ArrayList Object as String Array.
Try this
Iterator<String[]> it = al.iterator();
while(it.hasNext()){
String temp [] = it.next();
for(int i = 0; i < temp.length; i++) {
System.out.println(temp.length);
}
}
your new String[]
requires size, because you're making new array i.e
String[] myStringArray = new String[5];
also, your iteration to print values make no sense, try :
for(String[] stringArray: al) {
System.out.println("Size: " + stringArray.length);
for(String s: stringArray) {
System.out.println(s);
}
}
I am trying to combine multiple String lists.
Say I have two (could be more) lists of the same size:
List<String> list1 = Arrays.asList("1One","1Two","1Three");
List<String> list2 = Arrays.asList("2One","2Two","2Three");
I want to combine the value of the corresponding indexes and place them into a new list:
List3 = new {"1One2One", "1Two2Two", "1Three2Three"};
Currently I have a list of 2 objects, each object contains the list that I want to combine the elements within.
So I want to combine element 1 in the list from object 1 with element 1 from the list from object 2.
This is what I have attempted:
public void generateFileList(List<Object> cl){
int count = 0;
String temp = "";
for(int i = 0; i < cl.size(); i++){
for (int x = 0; x < cl.get(i).getItemList().size(); x++) {
if (count == x){
temp += cl.get(i).getListItem(x);
break;
}
}
count++;
textList.add(temp);
}
}
public void test(){
for(String s : textList){
System.out.println("List Element - " + s);
}
System.out.println(textList.size());
}
Which prints out:
List Element - 1One
List Element - 1One1Three
What am I doing wrong here?
First, the code you have won't compile. It should be:
List<String> list1 = Arrays.asList("1One","1Two","1Three");
List<String> list2 = Arrays.asList("2One","2Two","2Three");
Next, it is best to use an Iterator than access a List by index:
public List<String> concat(final List<String> list1, final List<String> list2) {
final Iterator<String> i1 = list1.iterator();
final Iterator<String> i2 = list2.iterator();
final List<String> combined = new ArrayList<>();
while (i1.hasNext() && i2.hasNext()) {
combined.add(i1.next() + i2.next());
}
return combined;
}
For an arbitrary number of List:
public List<String> concat(final List<String>... lists) {
final List<Iterator<String>> it = new LinkedList<>();
for (List<String> l : lists) {
it.add(l.iterator());
}
final List<String> combined = new ArrayList<>();
outer:
while (true) {
final StringBuilder sb = new StringBuilder();
for (final Iterator<String> i : it) {
if (!i.hasNext()) {
break outer;
}
sb.append(i.next());
}
combined.add(sb.toString());
}
for (final Iterator<String> i : it) {
if (i.hasNext()) {
throw new IllegalArgumentException("Lists not the same length.");
}
}
return combined;
}
If the lists have the same size, just have a for loop from 0 to list size, and add in the new list the concatenation of the elements from the same position in the two lists, like for (int i =0; i< list1.size(); i++) { resultedlist.add(list1.get(i) + list2.get(i))}
Presuming the 2 lists are the same size:
List<String> list1 = new {"1One","1Two","1Three"};
List<String> list2 = new {"2One","2Two","2Three"};
List<String> list3 = new ArrayList<>();
for (int i = 0; i < list1.size(); i++) {
list3.add(list1.get(i) + list2.get(i));
}
I am trying to write a hierarchal block that puts elements into an ArrayList, all apart of a larger ArrayList. What the block does is take an existing input of text, and adds every line of text into elements of an ArrayList. Each Line is then created as an ArrayList of Strings, with each String being a word on that line (I used the String Split at spaces (" ") to perform this).
My problem is when trying to create this I needed to use the Arrays.asList (because a String Split returns a List)
Action Syllables = new AbstractAction("Syllables") {
public void actionPerformed(ActionEvent e) {
ArrayList<String> text = LinetoList(area);
//"text" is a String ArrayList of every "line" in a piece of text
//LinetoList is a method that returns an ArrayList based on each new line
ArrayList<ArrayList> words = new ArrayList();
for (int i = 0; i < text.size(); i++) {
ArrayList sentence = (ArrayList) Arrays.asList(text.get(i).split(" "));
/*Sentence is currently a list, however, changing the type to an Array
* or Arraylist Changes nothing */
words.add(sentence);
}
for (int k = 0; k < words.size(); k++) {
for (int i= 0; i < words.get(k).size(); i ++) {
System.out.println(words.get(k).get(i));
}
}
}
};
This was my original Method which return the error. I have since adjusted slightly, which no longer returns an error BUT, doesn't return anything.
Action Syllables = new AbstractAction("Syllables") {
public void actionPerformed(ActionEvent e) {
ArrayList<String> text = LinetoList(area);
//"text" is a String ArrayList of every "line" in a piece of text
//LinetoList is a method that returns an ArrayList based on each new "line"
ArrayList<ArrayList> words = new ArrayList();
for (int i = 0; i < text.size(); i++) {
ArrayList <String> sentences = new ArrayList();
String sentence[] = text.get(i).split(" ");
sentence = sentences.toArray(sentence);
/*Sentence is currently a list, however, changing the type to an Array
* or Arraylist Changes nothing */
words.add(sentences);
}
if (words.size() == 0)
{System.out.println("Theres nothing here"); }
else {
for (int k = 0; k < words.size(); k++) {
for (int i= 0; i < words.get(k).size(); i ++) {
System.out.println(words.get(k).get(i));}
}
}
}
};
Any feedback or ideas on how to approach a solution is greatly appreciated.
EDIT: Some people asked for the LinetoList function. A majority of the program uses ArrayLists of strings which is why it's so heavily used here.
private static ArrayList<String> LinetoList(JTextArea textArea) {
String s[] = textArea.getText().split("\\r?\\n");
ArrayList<String>arrList = new ArrayList<>(Arrays.asList(s)) ;
return arrList;
}
I don't actually follow:
String sentence[] = text.get(i).split(" "); // here you have array
sentence = sentences.toArray(sentence); // WTF?
And now about that WTF mark - you are filling sencence array with content of sentences. WHat is better, I don't see declaration of sentences but I guess it is just empty right? Thats why you see it empty all the time. As for me, lot of strange code and useless comments in it.
1) Arrays.asList does not return java.util.ArrayList, if you want it to be ArrayList, then you need to do ArrayList sentence = new ArrayList( Arrays.asList(text.get(i).split(" ")));
2) toArray method puts all elements from collection into array. in your case, collection is empty as you are creating almost before you call method
So after taking a look at the comments on HOW the toArray and asList work, I tried a different approach that was based more on my linetolist function
the result was
Action Syllables = new AbstractAction("Syllables") {
public void actionPerformed(ActionEvent e) {
ArrayList<ArrayList> words = new ArrayList();
ArrayList<ArrayList> splitLines = new ArrayList();
ArrayList<String> characters = new ArrayList();
//^^goes to (As hierarchey )
ArrayList<String> text = LinetoList(area);
//text is a String ArrayList of every line in a text
//LinetoList is a method that returns an ArrayList based on each new line
for (int i = 0; i < text.size(); i++) {
//for each line we have
String sentence[] = text.get(i).split(" ");
ArrayList<String> splitText = new ArrayList<>(Arrays.asList(sentence));
words.add(splitText);
}
for (int j = 0; j < words.size(); j++) {
String sentence [] = text.get(j).split(" ");
ArrayList<String> splitText = new ArrayList<>(Arrays.asList(sentence));
ArrayList<ArrayList> SplitWords = new ArrayList();
for (int i =0; i < sentence.length; i++) {
ArrayList<Character> SplitCharacters = new ArrayList<Character>();
for (int k = 0; k < splitText.get(i).length(); k ++) {
SplitCharacters.add(splitText.get(i).charAt(k));
}
SplitWords.add(SplitCharacters);
}
splitLines.add(SplitWords);
if (words.size() == 0)
{System.out.println("Theres nothing here"); }
else {
for (int k = 0; k < words.size(); k++) {
System.out.println("\n");
for (int i= 0; i < words.get(k).size(); i ++) {
System.out.println(words.get(k).get(i));
}
}
System.out.println("That was the original method \n");
for (int k = 0; k < splitLines.size(); k++) {
System.out.println(splitLines.get(k).toString() + "\n");
}
}
}
}
};
I included two different approaches to this problem, one that simplifies things as an ArrayList of words and one that gives an ArrayList of ArrayList of Characters (or a array list of words which hold letters)
Thanks for all the help. Hopefully anyone else can take something away from my blunders.
Hi everybody I am trying to get values from an ArrayList I created. I have some indexes, and I want to print the data ONLY between the indexes I want, so far I ave done this, but it does not seem to work. I think the get() is not valid for want I want... Any ideas?
public static void main(String[] args) throws Exception {
Scanner dataSc = new Scanner(new FileReader("StudData1.txt"));
ArrayList<String> ArrayData = new ArrayList<String>();
ArrayList<String> idData = new ArrayList<String>();
ArrayList<String> idIndex = new ArrayList<String>();
int b = 0;
int a = 0;
int i = 0;
while (dataSc.hasNextLine()) {
String data = dataSc.nextLine();
ArrayData.add(i, data);
if (data.contains("ID: ")) {
idData.add(a, data);
idData.set(a, (idData.get(a).replaceAll("[\\D]", "")));
a++;
b++;
}
i++;
idIndex.add(b, Integer.toString(i));
}
int idSt1 = Integer.parseInt(idData.get(0));
int idSt2 = Integer.parseInt(idData.get(1));
int idSt3 = Integer.parseInt(idData.get(2));
int idxID1 = Integer.parseInt(idIndex.get(0));
int idxID2 = Integer.parseInt(idIndex.get(1));
int idxId3 = Integer.parseInt(idIndex.get(2));
if (idSt1 < idSt2 && idSt2 < idSt3) {
System.out.println(ArrayData.get(idxID1-3 , idxID2-3 );}
}
}
}
Its easy done with a for-loop.
for(int i = startindex+1; i<endindex; i++) {
System.out.println(ArrayData.get(i));
}
This loop will print all objects in the arraylist that are between the given indices.
But there is no method called get() which returns a collection of items that are between to given indices, you can only use the subList(arg0, arg1) method to creat a subcollection and then iterate over this subcollection. Take a look at the Docs http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#get%28int%29
Example:
List<String> al = new ArrayList<>();
al.add("a");
al.add("b");
al.add("c");
al.add("d");
List<String> sublist = al.subList(0, 3); //inclusive index 0, exclusive index 3
for(String s : sublist)
System.out.println(s);
Output: a, b, c
Problem is in your code:
System.out.println(ArrayData.get(idxID1-3 , idxID2-3 );
The get method of class ArrayList accepts only one argument, here you are passing two.
You can use subList(int fromIndex, int toIndex) to get your desired result.
You can take range of values by index from ArrayList as follows.
List<String> list=new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
for(int i=0;i<4;i++){
if(i<=2 && i>=1){
System.out.println(list.get(i));
}
}
i would do it like that
if (idSt1 < idSt2 && idSt2 < idSt3) {
for (int j = idxID1-3; j < idxID2-3; j++){
System.out.println(ArrayData.get(j));
}
}
Am doing a simple android application.In that I am deleting an element from array using the following code.
arr_fav = {"1","2","3"};
for(int i= 0;i<arr_fav.length;i++)
{
if(current_id == Integer.parseInt(arr_fav[i]))
{
arr_fav[1] = null;
} }
By doing this am getting the array like arr_fav = {"1",null,"3"}.But I want like arr_fav = {"1","3"}.How to delete an element.Am new to this android development.Please help me to solve this.
its better to use arraylist
arr_fav = {"1","2","3"};
List<String> numlist = new ArrayList<String>();
for(int i= 0;i<arr_fav.length;i++)
{
if(current_id == Integer.parseInt(arr_fav[i]))
{
// No operation here
}
else
{
numlist.add(arr_fav[i]);
}
}
arr_fav = numlist .toArray(new String[numlist .size()]);
You don't.
Arrays can not be resized.
You would need to create a new (smaller) array, and copy the elements you wished to preserve into it.
A better Idea would be to use a List implementation that was dynamic. An ArrayList<Integer> for example.
Arrays in Java are not dynamic, you can use an ArrayList instead.
You can copy the array elements that you want into a new array
j = 0;
for(int i= 0;i<arr_fav.length;i++)
{
if(current_id != Integer.parseInt(arr_fav[i]))
{
arr_new[j++] = arr_fav[i];
} }
Use an ArrayList instead of an array. It supports features like deleting any element, dynamic size, and many more.
ArrayList<String> arr_fav_list = new ArrayList<String>();
arr_fav_list.addAll(arr_fav);
arr_fav_list.remove(1);
This will do the job ...
List x = new ArrayList(Arrays.asList(arr_fav));
x.remove(String.valueOf(current_id));
arr_fav = x.toArray();
try this:
ArrayList<String> rm = new ArrayList<String>();
rm .addAll(arr_fav);
rm .remove(1);
Try something like this
int[] intAry = new int[5];
// populate array with 0 to 4
for (int i=0; i < intAry.length; i++) {
intAry[i] = i;
}
List<Integer> aList = Arrays.asList(intAry); // change the array to a list of integers
aList.remove(3); // remove the item 3 (4th index)
aList.toArray(intAry); // convert list back to array
System.out.println("size of array=" + intAry.size()); // output array size should be 4
for (int i=0; i < intAry.length; i++) {
System.out.print(intAry[i] + " "); // should output "0 1 2 4 "
}
set
array_fav[1]=array_fav[2];
array_fav[2]=null;
You can do it using the following method..
public static String[] removeElements(String[] input, String deleteMe) {
List result = new LinkedList();
for(String item : input)
if(!deleteMe.equals(item))
result.add(item);
return result.toArray(input);
}
OR you could use ArrayUtils.
array = ArrayUtils.removeElement(array, element)
For simple arrays like this you can't do this in this way
here is the full sample code for this
int current_id = 2;
String[] arr_fav = { "1", "2", "3" };
for (int i = 0; i < arr_fav.length; i++) {
if (current_id == Integer.parseInt(arr_fav[i])) {
String[] arr_fav_tem = new String[arr_fav.length - 1];
arr_fav[1] = null;
int counter = 0;
for (int j = 0; j < arr_fav.length; j++) {
if (arr_fav[j] != null) {
arr_fav_tem[counter] = arr_fav[j];
counter++;
}
}
arr_fav = arr_fav_tem;
}
}
for (int i = 0; i < arr_fav.length; i++) {
System.out.println(arr_fav[i]);
}
String[] arr_fav =
{ "1", "2", "3" };
List<String> myList = Arrays.asList(arr_fav);
String currentId = String.valueOf(current_id);
for (int i = 0; i < arr_fav.length; i++)
{
if (arr_fav[i].equals(currentId))
{
myList.remove(i);
}
}
private String[] removeItem(String[] names,
int position) {
ArrayList<String> al_temp=new ArrayList<String>();// temporary ArrayList
for(int i=0;i<names.length;i++)
{
al_temp.add(names[i]);
}
al_temp.remove(position);
names= new String[al_temp.size()];//array cleared with new size
for(int i=0;i<al_temp.size();i++)
{
names[i]=al_temp.get(i);
}
return names;
}
Copy this method:
private static String[] deleteElement(String stringToDelete, String[] array) {
String[] result = new String[array.length];
int index = 0;
ArrayList<String> rm = new ArrayList<String>();
for(int i = 0; i < array.length; i++) {
rm.add(array[i]);
}
for(int i = 0; i < array.length; i++) {
if(array[i].equals(poistettava)) {
index = i;
}
}
rm.remove(index);
result = rm.toArray(new String[rm.size()]);
return result;
}
To delete element:
String[] array = {"1", "2", "3"};
array = deleteElement("3", array);