Is there any possibility to merge two elements of ArrayList?
This is my array = [u,s,m,a,t,t]
and I want to have something like this = [us,matt]
I've tried to use toString(), and replace('',''), but it merges whole array [usmatt].
Any other options?
I don't know exactly what you mean but what you try to achieve could be done this way:
Pseudo-code:
String[] array1 = [u,s,m,a,t,t]
String a = array[0]+array[1]
String b = array[2]+array[3]+array[4]+array[5]
String[] array2 = [a,b]
Try this: (For any length ArrayList.)
public static void MergeArrayList() {
ArrayList<Character> Array = new ArrayList<Character>() {{ add('u');add('s');
add('m');add('a');add('t');add('t');}};
ArrayList<String> newArray = new ArrayList<>();
int n=2; // Change this to indicate where you need to make the cut.
String str="";
for (int i=0;i<Array.size();i++) {
if (i==n) {
newArray.add(str);
str="";
}
str += Array.get(i);
}
newArray.add(str);
System.out.println(Array);
System.out.println(newArray);
}
Related
The user is allowed to play with an array of strings. They can add strings to the array, remove strings from the array, search for strings in the array, and eventually they will be able to sort the array. The sorting is what is messing me up. I've tried a few different approaches. The first approach was to convert the array into an ArrayList and use Collections to sort the ArrayList, which would be converted back into the static class array. It doesn't work. The second approach I tried was to iterate through the array and try to sort only the strings added by the user instead of everything in the array (since there are some null values in the array). Perhaps I should iterate through the array and then store the non-null values into a new array that I can then sort? But what if I want to add more strings after sorting the new array? That's why I stopped with the second solution. The third attempt was to use Arrays.sort() on my array but for some reason it does not work.
Here is the exception:
Exception in thread "main" java.lang.NullPointerException
at java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:290)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:157)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:146)
at java.util.Arrays.sort(Arrays.java:472)
at java.util.Collections.sort(Collections.java:155)
at testingSearch.sortArray(testingSearch.java:93)
at testingSearch.main(testingSearch.java:42)
Here is my code:
import java.util.Scanner;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class testingSearch {
static String[] strArray;
static {
strArray = new String[5];
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while(true){
System.out.println("1. Add string to the string array.");
System.out.println("2. Remove string from the string array.");
System.out.println("3. Display strings in string array.");
System.out.println("4. Search the string array for a string.");
System.out.println("5. Sort the strings in the string array.");
int userChoice = 0;
userChoice = input.nextInt();
switch(userChoice) {
case 1:
addString();
break;
case 2:
removeString();
break;
case 3:
displayStrings();
break;
case 4:
searchArray();
break;
case 5:
sortArray();
break;
}
}
}
public static void addString(){
Scanner input = new Scanner(System.in);
System.out.println("What string do you want to add?");
String userInput;
userInput = input.nextLine();
ArrayList<String> stringList = new ArrayList<String> (Arrays.asList(strArray));
stringList.add(userInput);
strArray = stringList.toArray(strArray);
}
public static void removeString(){
Scanner input = new Scanner(System.in);
System.out.println("What string do you want to remove?");
String userInput;
userInput = input.nextLine();
ArrayList<String> stringList = new ArrayList<String> (Arrays.asList(strArray));
stringList.remove(userInput);
strArray = stringList.toArray(strArray);
}
public static void displayStrings(){
for (String s: strArray){
if (!(s == null)){
System.out.println(s);
}
}
}
public static void searchArray(){
Scanner input = new Scanner(System.in);
System.out.println("What string do you want to search the array for?");
String userInput;
userInput = input.nextLine();
ArrayList<String> stringList = new ArrayList<String>(Arrays.asList(strArray));
if (stringList.contains(userInput)){
System.out.println("The string array contains that string!");
}
else {
System.out.println("The string array does not contain that string...");
}
}
public static void sortArray(){
/*ArrayList<String> stringList = new ArrayList<String> (Arrays.asList(strArray));
Collections.sort(stringList);
strArray = stringList.toArray(strArray);*/
/*for (String s: strArray) {
if (!(s == null)){
Arrays.sort(strArray);
}
}*/
List<String> stringList = new ArrayList<String>(Arrays.asList(strArray));
Collections.sort(stringList);
strArray = stringList.toArray(strArray);
//Arrays.sort(strArray);
}
}
The reason you're getting NullPointerExceptions can be explained by the javadoc for Arrays#sort() (emphasis mine):
Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. All elements in the array must implement the Comparable interface.
Because Arrays.sort() expects Comparable elements and not null values, you end up with a NullPointerException when the method tries to call compareTo().
The fix-this-now way of solving this would be to simply make sure all null elements in your array are replaced with something non-null, such as "". So loop through your array at creation and after removing a String and set null elements to "". However, this solution probably wouldn't perform too well for your code, as it requires another loop after every String is removed, which could grow onerous. At least it won't require you to create a bunch of objects, due to the magic of the String pool, so it's a bit better than what you might do with a different object.
A better solution would be to simply use ArrayList<String> instead of a raw array; after all, you're already using one to manage addString() and removeString(), so you would have less converting from array to ArrayList and back to do. In addition, you wouldn't need to worry about NPEs when sorting (at least for your use case; adding null to a Collection would still result in NPEs when sorting).
You can also just use a raw array, but managing that would get kind of annoying, so I wouldn't recommend that. If you do it right you won't have to worry about NPEs though.
No problem! Here you go:
1. Create a new array
2. Insert items to that array, in the right order
public class sorter {
public static void main(String[] args){
String[] array = new String[]{"HI", "BYE", null, "SUP", ":)"};
//Sort:
String[] newArray = new String[array.length];
int index = 0;
for(int m = 0 ; m < newArray.length; m++){
String leastString = null;
int i = 0;
for(i = 0; i < array.length; i++){
if(leastString==null&&array[i]!=null){
leastString = array[i];
break;
}
}
for(int j = i+1; j < newArray.length; j++){
if(array[j]!=null){
if(array[j].compareTo(array[i])<0){
leastString = array[j];
i = j;
}
}
}
if(i==newArray.length)break;
newArray[m] = leastString;
array[i] = null;
}
for(String s : newArray){
System.out.println(s);
}
}
}
This prints:
:)
BYE
HI
SUP
null
EDIT: Another very simple way to solve this in a very effiecient manner, is to use ArrayList:
public class AClass {
public static void main(String[] args){
String[] array = new String[]{"HI", "BYE", null, "SUP", ":)"};
//Sort:
ArrayList<String> newArray = new ArrayList<String>();
for(String s : array){
if(s!=null){
newArray.add(s);
}
}
Collections.sort(newArray);
String[] retval = new String[newArray.size()];
retval = newArray.toArray(retval);
for(String s : retval){
System.out.println(s);
}
}
}
I guess the simple way of doing things really would be:
static String[] strArray;
static {
strArray = new String[5];
for(int i = 0, i < strArray.length; i++)
{
strArray[i] = "";
}
}
And then just call
Arrays.sort(strArray);
When you want to sort it. If that doesn't work, although I think it should; your initial approach would have been the following:
List<String> stringList = new ArrayList<String>();
for(int i = 0; i < strArray.length; i++)
{
stringList.add(strArray[i]);
}
Collections.sort(stringList);
strArray = stringList.toArray(new String[stringList.size()]);
Although it clearly doesn't seem very memory-friendly.
I have an Arraylist that I want to convert to a double[] array. I first convert the Arraylist to a String []. I then try to convert the String[] to a double[] but fail in the process. Here's the issue: the string contains some text, as well as some numbers with decimals. I want to convert only the numbers and decimals to a double[] array and simply delete the text. However, I only know how to delete the text with a String, not a String[]. Please take a look:
import java.util.ArrayList;
import java.util.List;
import jsc.independentsamples.SmirnovTest;
public class example {
public static void main(String[] arg) throws Exception {
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
list1.add("RSP0001,1.11,1.22");
list1.add("RSP0002,2.11,2.22");
list1.add("RSP0003,3.11,3.22");
list1.add("RSP0004,4.11,4.22");
String[] str1 = new String[list1.size()];
str1 = list1.toArray(str1);
str1.replaceAll("RSP_\\d+","");
double array1 = Double.parseDouble(str1);
System.out.println(array1);
}
}
Two errors come from this: the first is a "cannot find symbol" error at str1.replaceAll. The second is a "method parseDouble" error at "Double.parseDouble". The issue there is I need a String instead of a String[].
Any ideas on how to convert my String[] to a double[] ?
Thanks,
kjm
You need to split each String in list1 on "," and attempt to parse each String that gets split out:
ArrayList<Double[]> results = Lists.newArrayList();
for( String s : list1 ) {
String[] splitStrings = s.split(",");
Double[] doublesForCurrentString = new Double[splitStrings.length];
for(int i=0; i<splitStrings.length; i++){
try {
doublesForCurrentString[i] = Double.valueOf(splitStrings[i]);
} catch( NumberFormatException ex ) {
// No action.
}
}
results.add(doublesForCurrentString);
}
Double[][] doubleArray = (Double[][])results.toArray();
Crucial points:
EDIT: As #Tim Herold points out, you're probably better of performance-wise avoiding attempting to parse content you know to be non-numeric. In this case, I'd still split first and then just put in code that prevents you from attempting to parseDouble() on the first split String in each line, rather than trying to do String replacement before the split; that will be faster (and if we're not concerned about performance, then try/catch is perfectly fine and more readable). ORIGINAL: You need a try/catch when you try to parse the doubles, in case there's any invalid input. Bonus: you don't need to remove the non-numeric text now, you can just let this try/catch handle it.
Your strings have two doubles in each of them. You're not going to be able to just strip the text at the beginning and then parse the rest, because it's not going to be a valid double.
ArrayLists are generally easier to use; I'd opt for returning ArrayList<Double> (or ArrayList<ArrayList<Double>>) over Double[] or Double[][] any day of the week. There are certainly situations where I'd do differently, but yours doesn't sound like one of them to me.
Loop throug the Array:
foreach String[]
double[counter] = parseToDouble(String[counter])
EDIT:
Java:
String[] str1 = list1.toArray(str1);
double[] dou1 = new double[str1.length]
for(int counter = 0; counter < str1.length;counter++)
dou1[counter] = Double.parseDouble(str1[counter].replaceAll("RSP_\\d+",""));
Use this
String[] str1 = new String[list1.size()];
str1 = list1.toArray(str1);
double[] doubleArray = new double[str1.length]
int i=0;
for(String s:str1){
doubleArray[i] = Double.valueOf(s.trim());
i++;
}
This will do the work.
double[] doubles = new double[array1.length];
for(int i=0; i<array1.length; i++){
doubles[i] = Double.valueOf(array1[i])
}
Thanks SmartLemon for the edit, you could do this too instead of using a String[]:
double[] doubles = new double[list1.size()];
for(int i=0; i<list1.size(); i++){
doubles[i] = Double.valueOf(list1.get(i).replace("RSP_\\d+",""));
}
EDIT: So yes, you need a delimiter:
double[] doubles = new double[array1.length*2]; //multiply by 2 because you really have 8 numbers not 4
String [] array2 = null;
for(String string: array1) {
array2 = string.split(",");
for(int i=0; i<array2.length; i++){
doubles[i] = Double.valueOf(array2[i]);
}
}
this should do the work for sure.
I would do this:
make array
convert to string
then this code
for (String s: list1) {
boolean obtained = false;
double tempD;
try {
tempD = Double.parseDouble(s);
obtained = true;
} catch (Exception e) {
e.printStackTrace();
}
if (obtained) {
list2.add(tempD);
}
}
I have written this code, but at run time I have this error:
[Ljava.lang.Object; cannot be cast to [[Ljava.lang.String;
please help me, thanks!!!
public java.util.List<String> concatAll(java.util.List<java.util.List<String>> mergedList) {
java.lang.String [][] mergedArray = (String[][])mergedList.toArray();
Iterator<java.util.List<String>> itr = mergedList.iterator();
java.util.List<String> list1 = itr.next();
java.lang.String [] firstArray = (String[])list1.toArray();
int totalLength = firstArray.length;
for (String[] array : mergedArray) {
totalLength += array.length;
}
String[] result = Arrays.copyOf(firstArray, totalLength);
int offset = firstArray.length;
for (String[] array : mergedArray) {
System.arraycopy(array, 0, result, offset, array.length);
offset += array.length;
}
java.util.List<String> finalList = Arrays.asList(result);
for (String list : finalList)
System.out.println(list);
return finalList;
}
mergedList.toArray() creates a singly indexed array typed as objects.
Each of the objects it contains is in fact a (singly-indexed) list of strings, though with this call syntax the type is not known at compile-time. It is not an array of strings, as would be needed for your cast to work.
Since your concatAll is trying to convert a List<List<String>> into a List<String> by some sort of concatenation operation, it may be best to do this without ever converting to a String[][] at all, but if you do want that conversion, it can be done as follows:
private String[][] toDoubleIndexArray(List<List<String>> mergedList) {
String[][] result = new String[mergedList.size()][];
for (int i = 0; i< mergedList.size(); i++) {
List<String> currentList = mergedList.get(i);
result[i] = currentList.toArray(new String[currentList.size()]);
}
return result;
}
Original answer, not quite correct as noted by Xavi Lopez in comments:
Since mergedList has type List<List<String>>,
mergedList.toArray() has type List<String>[], i.e., it's an array of lists, and not a doubly indexed array.
There's no out-of-the-box method, but it's fairly straightforward to do by hand:
// Create the outer dimension of the array, with the same size as the total list
String[][] mergedArray = new String[mergedList.size()][];
// Now iterate over each nested list and convert them into the String[]
// instances that form the inner dimension
for (int i = 0; i < mergedList.size(); i++) {
mergedArray[i] = mergedList.get(i).toArray(new String[0]);
}
A slightly more efficient version of the loop body would be
List<String> innerList = mergedList.get(i);
String[] innerAsArray = innerList.toArray(new String[innerList.size()]);
mergedArray[i] = innerAsArray;
as this avoids the array resizing that would be required in my initial example (the new String[0] isn't large enough to hold the list elements). But quite frankly, unless this was a performance critical loop, I'd prefer the first version as I find it slightly clearer to see what's going on.
Hey you cannot convert the Multi dimentional String list to String array directly. Add the below code before trying to use the mergedArray:
/** Create Array **/
String [][] mergedArray = new String[mergedList.size()][];
/** Initialize array from list **/
for(int i=0; i< mergedList.size(); i++){
mergedArray[i] = mergedList.get(i).toArray(new String[0]);
}
This should do the trick
I think your return type is wrong if your intention is to return an array of array.
Try this:
public String[][] concatAll(java.util.List<java.util.List<String>> mergedList) {
//java.lang.String [][] mergedArray = (String[][])mergedList.toArray();
java.lang.String[][] mergedArray = new String[mergedList.size()][];
Iterator<java.util.List<String>> itr = mergedList.iterator();
int count = 0;
while (itr.hasNext())
{
java.util.List<String> list1 = itr.next();
String[] array1 = list1.toArray(new String[list1.size()]);
mergedArray[count++] = array1;
}
return mergedArray;
}
You can't convert a
List<List<String>>
to a String[][] by using the out of the box toArray functionality. This would only work if you had:
List<String[]>.
I have an ArrayList with values like "abcd#xyz" and "mnop#qrs". I want to convert it into an Array and then split it with # as delimiter and have abcd,mnop in an array and xyz,qrs in another array. I tried the following code:
String dsf[] = new String[al.size()];
for(int i =0;i<al.size();i++){
dsf[i] = al.get(i);
}
But it failed saying "Ljava.lang.String;#57ba57ba"
You don't need to reinvent the wheel, here's the toArray() method:
String []dsf = new String[al.size()];
al.toArray(dsf);
List<String> list=new ArrayList<String>();
list.add("sravan");
list.add("vasu");
list.add("raki");
String names[]=list.toArray(new String[list.size()])
List<String> list=new ArrayList<String>();
list.add("sravan");
list.add("vasu");
list.add("raki");
String names[]=list.toArray(new String[0]);
if you see the last line (new String[0]), you don't have to give the size, there are time when we don't know the length of the list, so to start with giving it as 0 , the constructed array will resize.
import java.util.*;
public class arrayList {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
ArrayList<String > x=new ArrayList<>();
//inserting element
x.add(sc.next());
x.add(sc.next());
x.add(sc.next());
x.add(sc.next());
x.add(sc.next());
//to show element
System.out.println(x);
//converting arraylist to stringarray
String[]a=x.toArray(new String[x.size()]);
for(String s:a)
System.out.print(s+" ");
}
}
String[] values = new String[arrayList.size()];
for (int i = 0; i < arrayList.size(); i++) {
values[i] = arrayList.get(i).type;
}
What you did with the iteration is not wrong from what I can make of it based on the question. It gives you a valid array of String objects. Like mentioned in another answer it is however easier to use the toArray() method available for the ArrayList object => http://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html#toArray%28%29
Just a side note. If you would iterate your dsf array properly and print each element on its own you would get valid output. Like this:
for(String str : dsf){
System.out.println(str);
}
What you probably tried to do was print the complete Array object at once since that would give an object memory address like you got in your question. If you see that kind of output you need to provide a toString() method for the object you're printing.
package com.v4common.shared.beans.audittrail;
import java.util.ArrayList;
import java.util.List;
public class test1 {
public static void main(String arg[]){
List<String> list = new ArrayList<String>();
list.add("abcd#xyz");
list.add("mnop#qrs");
Object[] s = list.toArray();
String[] s1= new String[list.size()];
String[] s2= new String[list.size()];
for(int i=0;i<s.length;i++){
if(s[i] instanceof String){
String temp = (String)s[i];
if(temp.contains("#")){
String[] tempString = temp.split("#");
for(int j=0;j<tempString.length;j++) {
s1[i] = tempString[0];
s2[i] = tempString[1];
}
}
}
}
System.out.println(s1.length);
System.out.println(s2.length);
System.out.println(s1[0]);
System.out.println(s1[1]);
}
}
Here is the solution for you given scenario -
List<String>ls = new ArrayList<String>();
ls.add("dfsa#FSDfsd");
ls.add("dfsdaor#ooiui");
String[] firstArray = new String[ls.size()];
firstArray =ls.toArray(firstArray);
String[] secondArray = new String[ls.size()];
for(int i=0;i<ls.size();i++){
secondArray[i]=firstArray[i].split("#")[0];
firstArray[i]=firstArray[i].split("#")[1];
}
This is the right answer you want and this solution i have run my self on netbeans
ArrayList a=new ArrayList();
a.add(1);
a.add(3);
a.add(4);
a.add(5);
a.add(8);
a.add(12);
int b[]= new int [6];
Integer m[] = new Integer[a.size()];//***Very important conversion to array*****
m=(Integer[]) a.toArray(m);
for(int i=0;i<a.size();i++)
{
b[i]=m[i];
System.out.println(b[i]);
}
System.out.println(a.size());
This can be done using stream:
List<String> stringList = Arrays.asList("abc#bcd", "mno#pqr");
List<String[]> objects = stringList.stream()
.map(s -> s.split("#"))
.collect(Collectors.toList());
The return value would be arrays of split string.
This avoids converting the arraylist to an array and performing the operation.
NameOfArray.toArray(new String[0])
This will convert ArrayList to Array in java
// A Java program to convert an ArrayList to arr[]
import java.io.*;
import java.util.List;
import java.util.ArrayList;
class Main {
public static void main(String[] args)
{
List<Integer> al = new ArrayList<Integer>();
al.add(10);
al.add(20);
al.add(30);
al.add(40);
Integer[] arr = new Integer[al.size()];
arr = al.toArray(arr);
for (Integer x : arr)
System.out.print(x + " ");
}
}
I have an arraylist, say arr. Now this arraylist stores numbers as strings. now i want to convert this arraylist to integer type. So how can i do that???
ArrayList arr = new ArrayList();
String a="Mode set - In Service", b="Mode set - Out of Service";
if(line.contains(a) || line.contains(b)) {
StringTokenizer st = new StringTokenizer(line, ":Mode set - Out of Service In Service");
while(st.hasMoreTokens()) {
arr.add(st.nextToken());
}
}
Since you're using an untyped List arr, you'll need to cast to String before performing parseInt:
List<Integer> arrayOfInts = new ArrayList<Integer>();
for (Object str : arr) {
arrayOfInts.add(Integer.parseInt((String)str));
}
I recommend that you define arr as follows:
List<String> arr = new ArrayList<String>();
That makes the cast in the conversion unnecessary.
run the below code,i hope it meets you requirement.
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
ArrayList<String> strArrayList= new ArrayList<String>();
strArrayList.add("1");
strArrayList.add("11");
strArrayList.add("111");
strArrayList.add("12343");
strArrayList.add("18475");
int[] ArrayRes = new int[strArrayList.size()];
int i = 0;
int x = 0;
for (String s : strArrayList)
{
ArrayRes[i] = Integer.parseInt(s);
System.out.println(ArrayRes[i]);
i++;
}
}
}
Output:
1
11
111
12343
18475
To convert to an integer array, you will input as a string array then go through each one and change it to an int.
public int[] convertStringArraytoIntArray(String[] sarray) throws Exception {
if (sarray != null) {
//new int for each string
int intarray[] = new int[sarray.length];
//for each int blah blah to array length i
for (int i = 0; i < sarray.length; i++) {
intarray[i] = Integer.parseInt(sarray[i]);
}
return intarray;
}
return null;
}
final List<String> strs = new ArrayList();
strs.add("1");
strs.add("2");
Integer[] ints = new Integer[strs.size()];
for (int i = 0; i<strs.size(); i++){
ints[i] = Integer.parseInt(strs.get(i));
}
use the Integer.parseInt() method.
http://www.java2s.com/Code/Java/Language-Basics/Convertstringtoint.htm
If you know that you have an arraylist of string but in your you wil use the same list as list of integer so better while initializing array list specify that the array list must insert only int type of data
instead of writing ArrayList arr = new ArrayList();
you could have written ArrayList<Integer> arr = new ArrayList<Integer>();
Alternate solution
If you want to convert that list into Integer ArrayList then use following code
How to convert String ArrayList into ArrayList of int
ArrayList<String> oldList = new ArrayList<String>();
oldList.add(""+5);
oldList.add(""+5);
ArrayList<Integer> newList = new ArrayList<Integer>(oldList.size());
for (String myInt : oldList) {
newList.add(Integer.parseInt(myInt));
}