Extract String[] elements from a list - java

at my work I've got the following source code:
import java.util.ArrayList;
import java.util.List;
public class Temporaer
{
public static void main(String[] args)
{
List stringArrayList = new java.util.ArrayList();
stringArrayList.add(fillStringArrayElement("a", "b"));
stringArrayList.add(fillStringArrayElement("c", "d"));
String[] listElement;
/*
* I'm stuck here, because I don't know what I have to do
*/
System.out.println(listElement.length);
}
//Just a method to fill a list easily
private static String[] fillStringArrayElement (String firstElem, String secondElem)
{
String[] stringArrayListElement = new String[2];
stringArrayListElement[0] = firstElem;
stringArrayListElement[1] = secondElem;
return stringArrayListElement;
}
}
My goal is it to extract each list item and work with those.
I tried to use the toArray[T[]) method as mentioned here. Though it generates an java.lang.ArrayStoreException. Note: I cannot change the type of the list because the list is filled by an extern service. Maybe I have to convert the list first...
Can someone show me a way to achive my goal? Thanks in advanced.

Iterator is an interface in java used to iterate over a Collection like ArrayList or other Collection framework classes.
Before reading ArrayList make sure values are available using the size() method.
Here a sample working snippet for your problem.
String [] myArray ;
if (stringArrayList.size()>0){
Iterator<String [] > i = stringArrayList.iterator();
while(i.hasNext()){
myArray = i.next();
for(String s : myArray)
System.out.println(s);
}
}
}
Don't use Raw ArrayList, instead use Generics

Use this:
List<String[]> stringArrayList = new java.util.ArrayList<String[]>();
stringArrayList.add(new String[]{"a", "b"});
stringArrayList.add(new String[]{"c", "d"});
//if you cant to convert the stringArrayList to an array:
String[][] listElement = stringArrayList.toArray(new String[0][]);
for (String[] inArr : listElement){
for (String e : inArr){
System.out.print(e + " ");
}
System.out.println();
}

String[] listElement;
Above statements is incorrect because you are keeping arrays in list so your listElement must contain String[] .
String [][] listElement
Something like below.
listElement=stringArrayList.toArray(new String[stringArrayList.size()][]);

Related

Converting array list to a string array

I've been trying to convert my string array list to a string array so I can print it but have been unable to do so.
This is the class I have, randomQuestion which takes in an array list from the gameQuestions method in the same class.
I have never tried to convert an array list using a loop before hence the difficulty, I was able to convert it fine with the code
String[] questions = data1.toArray(new String[]{});
But I need it to loop through using a for loop to store it in an array which I can then print one at a time once a question is answered successfully.
The error I'm receiving from netbeans is cannot find symbol
Symbol:methodtoArray(String[]) for the .toArray portion below.
public String[] randomQuestion(ArrayList data1) {
Collections.shuffle(data1);
for (int question = 0; question < 10; question++) {
ranquestions = data1.get(question).toArray(new String[10]);
}
return ranquestions;
}
Any help would be greatly appreciated.
You can use List.toArray(). Class List has a method:
<T> T[] toArray(T[] a);
Assuming you have an ArrayList<String>, you can use String.join(delimiter, wordList) in order to concatenate all the elements to a single String:
public static void main(String[] args) {
// example list
List<String> words = new ArrayList<String>();
words.add("You");
words.add("can");
words.add("concatenate");
words.add("these");
words.add("Strings");
words.add("in");
words.add("one");
words.add("line");
// concatenate the elements delimited by a whitespace
String sentence = String.join(" ", words);
// print the result
System.out.println(sentence);
}
The result of this example is
You can concatenate these Strings in one line
So using your list, String.join(" ", data1) would create a String with the elements of data1 delimited by a whitespace.
The question is how to create an array with only 10 elements of the list, if I understood correctly.
Streams (Java 8):
String[] ranquestions = data1.stream()
.limit(10)
.toArray(String[]::new);
Loop (based on question, avoiding unnecessary changes):
String[] ranquestions = new String[10];
for(int question = 0; question < 10; question++) {
ranquestions[question] = data1.get(question);
}
always assuming List<String> data1, if not some conversion is needed.
Example:
String[] ranquestions = data1.stream()
.limit(10)
.map(String::valueOf)
.toArray(String[]::new);
or, loop case:
ranquestions[question] = String.valueOf(data1.get(question));
You can do:
private String[] randomQuestions(ArrayList data){
Collections.shuffle(data);
return (String[]) data.toArray();
}
If you are sure you are getting a list of string (question) you can instead
private String[] randomQuestions(List<String> data){
Collections.shuffle(data);
return (String[]) data.toArray();
}
Edit 1
private static String[] randomQuestions(ArrayList data){
Collections.shuffle(data);
String[] randomQuestions = new String[data.size()];
for(int i=0; i<data.size(); i++){
randomQuestions[i] = String.valueOf(data.get(i));
}
return randomQuestions;
}

Removing Duplicates in an ArrayList by creating a Method

I have to write a method called removeDups that accepts an ArrayList of Strings and returns a copy of the ArrayList with all the duplicates removed. I have to return a new ArrayList with no duplicate basically.
import java.util.ArrayList;
public class Duplicates {
public static ArrayList <String> removeDups(ArrayList<String> myArray) {
for (String item: myArray ) {
ArrayList <String> noDuplicate = new ArrayList <String>();
if (!noDuplicate.contains(item)) {
noDuplicate.add(item);
}else
;
return noDuplicate;
}
}
}
As a beginner coder, I am having trouble writing this code.
You need to modify few things to make it work (and to have cleaner code):
when you do not need ArrayList<String> you should work with interface List<String>
you should initiate noDuplicate array in the first line of method
you should check the condition !noDuplicate.contains(item) and if so just add item to noDuplicate list
rename the method from removeDups to removeDuplicates
Working code:
public static List<String> removeDuplicates(List<String> myArray) {
List<String> noDuplicate = new ArrayList<>();
for (String item : myArray) {
if (!noDuplicate.contains(item)) {
noDuplicate.add(item);
}
}
return noDuplicate;
}
If you will take a look on Java streams you can do the same thing using:
List<String> noDuplicate = myArray.stream()
.distinct()
.collect(Collectors.toList());

How to iterate arraylist of arrayLists

I Have a list which is in
[
[SAM, 12/01/2015, 9A-6P],
[JAM, 12/02/2015, 9A-6P]
]
I need to iterate it.I tried the below code
for (int i = 0; i < list4.size(); i++) {
System.out.println("List" + list4.get(i).toString());
}
//this is giving me [SAM, 12/01/2015, 9A-6P]
but I want to iterate the above one also [SAM, 12/01/2015, 9A-6P].
Can anybody have idea?
You can and should use the fact that every List is also an Iterable. So you can use this:
// Idk what you list actually contains
// So I just use Object
List<List<Object>> listOfLists;
for(List<Object> aList : listOfLists) {
for(Object object : aList) {
// Do whatever you want with the object, e.g.
System.out.println(object);
}
}
Tried your case with below example. Hope it helps
import java.util.ArrayList;
import java.util.List;
public class IterateList {
public static void main(String[] args) {
List<List<String>> myList = new ArrayList<List<String>>();
List<String> list1 = new ArrayList<String>();
list1.add("SAM");
list1.add("12/01/2015");
list1.add("9A-6P");
List<String> list2 = new ArrayList<String>();
list2.add("JAM");
list2.add("12/01/2015");
list2.add("9A-6P");
myList.add(list1);
myList.add(list2);
for (List list : myList) {
for(int i=0; i<list.size();i++){
System.out.println(list.get(i));
}
}
}
}
Output:
SAM
12/01/2015
9A-6P
JAM
12/01/2015
9A-6P

Why i am getting "Remove type arguments" error for "List<String> list1 = new ArrayList<String>();"

i am trying to implementing ArrayList using String array.
while implementing i am getting Remove type arguments error in my eclipse.
ArrayList.java
import java.util.List;
public class ArrayList {
public static void main(String [] a)
{
String [] things = {"eggs","chicken","milk","butter"};
List<String> list1 = new ArrayList<String>();
for(String s: things)
list1.add(s);
String [] morethings = {"chicken","milk"};
List<String> list2 = (List<String>) new ArrayList ();
for(String y: morethings)
list2.add(y);
for(int i=0; i<list1.size();i++)
{
System.out.printf("%s ", list1.get(i));
}
}
}
You've defined your own ArrayList which is not a generic class. To use java.util.ArrayList simply rename your class to something else other than one of Java's built-in classes
You have used the class java.awt.List which is used for GUI List options such as creating a drop-down list, and thus one cannot use collectibles/data structure, Iterators with such a list.
You need to use java.util.List for implementing:
List>= new LinkedList>();

How to reverse a String array based on it's index value

I want to reverse this:
customArray = myArray;
nameArray = new String[myArray.size()];
for (int i = 0; i < myArray.size(); i++) {
idArray[i] = myArray.get(i).getUnitID();
nameArray[i] = myArray.get(i).getUnitName();
}
if (sortType == SORT)
Arrays.sort(idArray, Collections.reverseOrder());
Arrays.sort(nameArray, ...);
I know how to reverse this by using Arrays.sort(stringArray, Collections.reverseOrder()); but not by index value.
How can I reverse the order of my nameArray based on it's nameArray[i]?.. or even better, since my idArray is actually a list of unique ID's I would like to sort nameArray based on the idArray.
(Update: Now reversing an array of strings and not a list of strings.)
Use Collections.reverse together with Arrays.asList to reverse the array.
Example:
public static void main(String... args) {
String[] array = {"one", "two", "three"};
Collections.reverse(Arrays.asList(array)); // reverses the underlying list
System.out.println(Arrays.toString(array)); // prints [three, two, one]
}
The only solution to your problem is to use an OOP approach. After all, Java is an OOP Language. So instead of having two arrays:
int[] unitID
String[] unitName
which you can't sort in a way that the indexes stay corresponding, write a class Unit that implements Comparable<Unit> and use one array:
Unit[] units
then
Arrays.sort(units);
will do the job.
You would need your own class:
public class Unit implements Comparable<Unit> {
private int id;
private String name;
// Constructor
// Methods
#Override
public int compareTo(Unit other) {
// sorts by id
return this.id - other.id;
// to sort by name, use this:
// return this.name.compareTo(other.name);
}
}
Try this:
import java.util.Collections;
import java.util.List;
import java.util.Arrays;
public void reverseString(String[] stringArray){
List<String> list = Arrays.asList(stringArray);
Collections.reverse(list);
stringArray= (String[]) list.toArray();
}
String[] yourStringArray = new String[]{"Sunday", "Monday", "Tuesday", "Wednesday"};
reverseString(yourStringArray);
//result would be:
//"Wednesday","Tuesday", "Monday", "Sunday"

Categories