Split id and add to array - java

I have to split off the last two characters of an ID, the id may vary in length. example 56427R1 and R00220P3. Once the last two characters are split off, I need to add the first set of characters and the last two characters to an ArrayList. Thanks in advance.
I've tried the following
List<String> list = new ArrayList<String>();
list.add(clientValue.substring(0, clientValue.length()-2));
but was having trouble keeping the last 2 characters while removing the first half.
Resolved, repaired with the following code
ArrayList<String> list = new ArrayList<String>();
list.add(clientValue.substring(clientValue.length()-2));
list.add(clientValue.substring(0, clientValue.length()-2));

Use String.substring() with String.length() to split the string.
Use ArrayList<String>.add() to append to an ArrayList.
EDIT:
the code you have posted is correct: clientValue is not modified by the call to clientValue.substring() but returns a new String instance. Java String are immutable.
To complete your code:
List<String> list = new ArrayList<String>();
list.add(clientValue.substring(0, clientValue.length()-2));
list.add(clientValue.substring(clientValue.length()-2));

string tmp = "56427R1";
ArrayList<String> arrList = new ArrayList()<String>;
arrayList.add(tmp.substring(tmp.length() - 2));
arrayList.add(tmp.substring((tmp.length() - 2), tmp.length()));

You can do it easily like this:
String myID = "56427R1";
String extractedID = myID.substring((myID.length()-2), myID.length());
ArrayList<String> list = new ArrayList<String>;v
list.add(myID.substring((myID.length()-2)));
list.add(extractedID);
UPDATE:
String myID = "56427R1";
String extractedID = myID.substring((myID.length()-2), myID.length());
char[] a = extractedID.toCharArray();
char[] b = myID.substring(myID.length()-2).toCharArray();
ArrayList<Character> list = new ArrayList<Character>();
for(int i = 0; i < b.length; i++)
list.add(b[i]);
for(int j = 0; j < a.length; j++)
list.add(a[j]);

Related

How to order an array/list of int that is received as a string by input in Java

I was trying to test my skills and I try to do a test.
I receive the following input:
[7,11,10,6,9]
[21,24,25,23,26]
[116,115,117,120,121,119]
I need to sort all these values.
I try to do the following:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] parts = null;
List<String> linhas = new ArrayList<>();
for (int i = 0; i < 3; i++) {
String line = br.readLine();
line = line.replace("[","");
line = line.replace("]","");
line = line.replace(" ","");
System.out.println(line);
parts = line.split(",");
}
This way I got to show the output
7,11,10,6,9
21,24,25,23,26
116,115,117,120,121,119
The "String[parts]" got all values, but I don't know how to sort it, because the "parts" parameter is inside a "for loop".
How can I convert it to int/Integer and sort each line?
Assuming [7,11,10,6,9] be the input, we can try converting to a list of integers, and then sort that list:
String input = "[7,11,10,6,9]";
input = input.replaceAll("\\[(.*)\\]", "$1");
String[] vals = input.split(",");
List<Integer> output = Arrays.stream(vals)
.map(v -> Integer.parseInt(v))
.collect(Collectors.toList());
Collections.sort(output);
System.out.println(Arrays.toString(output.toArray()));
This prints:
[6, 7, 9, 10, 11]
Once you have parts you must convert this String[] into an int[]. To do this, first create an int[] for your results to go in. It must be the same size as your String[]:
int[] ints = new int[parts.length];
Then, iterate through the String[] and fill in values in the int[]:
for (int i = 0; i < parts.length; i++) {
ints[i] = Integer.parseInt(parts[i]); // converts a string containing an integer into its int value
}
Finally, to sort each line, a simple call to Arrays.sort(ints); will sort your array of integers.
Bonus:
This can be achieved more cleanly in a single line using Java 8 Streams, as follows:
List<Integer> sortedInts = Arrays.stream(parts).map(Integer::parseInt).sorted().collect(Collectors.toList());
You can do the replace() lines at once and split more cleanly with a regex:
parts = line.split("[\\[\\], ]+");
and use the Iterable technique that cameron1024 demonstrates in his answer. I think that using Iterable is a better choice for this use case than using Streams because the input size is trivially small and Streams has to spend more time to spin up.
The whole thing would look like:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] parts;
List<String> linhas = new ArrayList<>();
for (int i = 0; i < 3; i++) {
String line = br.readLine();
parts = line.split("[\\[\\] ,]+");
}
int ints[] = new int[parts.length];
for(int i = 0; i < parts.length; i++){
ints[i] = Integer.parseInt(parts[i]);
}
Arrays.sort(ints);

Take a List of Strings and double each character in an arraylist

I am trying to double each letter in a list of Strings in an array loop.
For example:
["abc","def"] --> ["aabbcc","ddeeff"]
ArrayList<String> aa;
aa = new ArrayList<String>();
String res = "";
for(int i=0;i<words.size();i++){
char at = aa.get(i);
res=res+at+at;
}
return res;
I am still new to coding and as you can see, my code is a mess. Help is appreciated. Thanks in advance
You some problems with your implementation:
You interact over words array but uses the index over the aa. As it was never added items to it, you will get an ArrayIndexOutOfBoundsException.
You issue a return res but this will return only one string, not an array of words.
According to your example this can be done this way:
public static ArrayList<String> doubleWords(ArrayList<String> input) {
ArrayList<String> result = new ArrayList<>();
for (String string : input) {
String word = "";
for (int i = 0; i < string.length(); i++) {
word += ""+string.charAt(i)+string.charAt(i);
}
result.add(word);
}
return result;
}
Your output for an ArrayList with [abc, def] will be [aabbcc, ddeeff].
You need to iterate through your list of words and then for each word in the list iterate through the characters in the string, like so:
public ArrayList<String> doubleWords(ArrayList<String> words) {
ArrayList<String> doubledWords = new ArrayList<String>();
for (String word : words) {
String newWord = "";
for (int i=0; i<word.length(); i++) {
newWord = newWord + word.substring(i, i+1) + word.substring(i, i+1);
}
doubledWords.add(newWord);
}
return doubledWords;
}
Since Java 8 this can also be achieved in the following way:
String input = "abc";
StringBuilder builder = new StringBuilder();
input.chars().forEach(value -> builder.append((char)value).append((char)value));
Remeber to convert the int value back to a char before you append it.
Output for above program:
System.out.println(builder.toString());
// aabbcc
//response list
ArrayList<String> aa;
aa = new ArrayList<String>();
StringBuilder sb = new StringBuilder() ;
String word;
// iterate list of words
for(int i=0; i < words.size(); i++){
//get word
word = words.get(i);
//iterate each character in word
for(int j =0; j < words; j++) {
//append each char twice in StringBuilder
sb.append(word[j).append(word[j]);
}
//add word to output list
aa.add(sb.toString());
//empty StringBuilder for next word
sb.setLength(0);
}
return aa;
It can be done only by java stream api without any temporary variables:
List<String> result = listOfWords.stream().
map(value -> String.valueOf( // new result String(doubled word)
value.chars() // get chars for each original string
.mapToObj(i-> (char)i) // cast each char from int to char type
.map(c -> String.valueOf(new char[]{c, c})) // create doubled char string
.collect(Collectors.joining()))) // concatenate all doubled chars
.collect(Collectors.toList()); // collect result to list

NullPointerException adding substring from string to array list

What I'm trying to do is add a substring from a String to an ArrayList. basically adding every letter in the string to an index in the ArrayList. After that i have a print statement just to see if the letters were added to the ArrayList (thats the second for loop under makearraylisOfChosenWord). However, when i run this with or without the print statement, it gives me a NullPointerException. Is it because I'm adding the letters to the arraylist in a wrong way in the first for loop?
thanks for the help
heres the code:
String[] wordList = {"apple", "orange", "strawberry", "banana"};
String chosenWord;
//Make an array list to hold one letter of the chosen word at each index
void makeArrayListOfChosenWord(){
ArrayList<String> lettersOfChosenWord = new ArrayList<String> ();
for (int i = 0; i < chosenWord.length(); i++) {
lettersOfChosenWord.add(chosenWord.substring(i, i+1));
}
for (int i = 0; i < lettersOfChosenWord.size(); i++) {
System.out.println((lettersOfChosenWord.get(i)).toString());
}
}
//Let the game pick a random word from the word list
void setRandomWord(){
int wordListLength = wordList.length;
int pickRandomWord = (int) (Math.random() * wordListLength);
String createRandomWord = wordList[pickRandomWord];
chosenWord = createRandomWord;
System.out.printf("the word is %s letters long", chosenWord.length());
}
I was just thinking about your problem and would try to use an ArrayList of Character instead of String. This is imo ok, because you mentioned that you are splitting up a String into single Characters, so ArrayList<Character>() seems a reasonable approach.
For splitting up the String I would make use of the method toCharArray():
String str = "abcd...";
ArrayList<Character> chars = new ArrayList<Character>();
for (char c : str.toCharArray()) {
chars.add(c);
}
If you call your setRandomWord method before you call makeArrayListOfChosenWord method no NullPointerException will be thrown. No if-check is needed in your code for this condition.

Is this correct sort method?

Is this correct method to sort ArrayList?
The problem is that the list is not sorted.
out = new StringTokenizer(input.toString());
n = (out.countTokens());
for (int i = 0; i < n; i++) {
String[] words = { out.nextToken().toString() };
final List<String> wordList = Arrays.asList(words);
Collections.sort(wordList);
System.out.println(wordList.toString());
}
Each of your words[] arrays is composed of a single string, obtained from the next token of your StringTokenizer. And you are iterating in exact order of the tokenization. So yes, your output will not be sorted. I presume you wanted to do something like this:
out = new StringTokenizer(input.toString());
int count = out.countTokens():
List<String> wordList = new ArrayList<String>(count);
for(int i = 0; i < count; i++) {
wordList.add(out.nextToken());
}
Collections.sort(wordList);
But, don't use the tokenizer class, its legacy. The following code will serve you better:
List<String> wordList = Arrays.asList(input.split("\\s"));
Collections.sort(wordList);
out.nextToken().toString() give you one string. Your array length should be 1, I presume.
Even if you put this into a loop, you sort at each loop, you have to sort outside the loop.
StringTokenizer out = new StringTokenizer( input.toString());
List<String> wordList = new ArrayList< String >();
while( out.hasMoreTokens()) {
wordList.add( out.nextToken());
}
Collections.sort( wordList );
System.out.println(wordList.toString());

How to convert String to ArrayList<String>

Let's say I have this String -
string = "AEIOU";
and I wanted to convert it to an ArrayList<String>, where each character is it's own individual String within the ArrayList<String>
[A, E, I, O, U]
EDIT: I do NOT want to convert to ArrayList<Character> (yes, that's very straightforward and I do pay attention in class), but I DO want to convert to an ArrayList<String>.
How would I do that?
transform the String into a char array,
char[] cArray = "AEIOU".toCharArray();
and while you iterate over the array, transform each char into a String, and then add it to the list,
List<String> list = new ArrayList<String>(cArray.length);
for(char c : cArray){
list.add(String.valueOf(c));
}
Loop and use String.charAt(i), to build the new list.
You can do it by using the split method and setting the delimiter as an empty string like this:
ArrayList<String> strings = new ArrayList<>(Arrays.asList(string.split("")));
First you have to define the arrayList and then iterate over the string and create a variable to hold the char at each point within the string. then you just use the add command. You will have to import the arraylist utility though.
String string = "AEIOU";
ArrayList<char> arrayList = new ArrayList<char>();
for (int i = 0; i < string.length; i++)
{
char c = string.charAt(i);
arrayList.add(c);
}
The import statement looks like : import java.util.ArrayList;
To set it as a string arrayList all you have to do is convert the char variables we gave you and convert it back to a string then add it: (And import the above statement)
ArrayList<String> arrayList = new ArrayList<String>();
String string = "AEIOU"
for (int i = 0; i < string.length; i++)
{
char c = string.charAt(i);
String answer = Character.toString(c);
arrayList.add(answer);
}
Since everyone is into doing homework this evening ...
String myString = "AEIOU";
List<String> myList = new ArrayList<String>(myString.length());
for (int i = 0; i < myString.length(); i++) {
myList.add(String.valueOf(myString.charAt(i)));
}
For a single line answer use the following code :
Arrays.asList(string .toCharArray());
Kotlin approach:
fun String.toArrayList(): ArrayList<String> {
return ArrayList(this.split("").drop(1).dropLast(1))
}
var letterArray = "abcd".toArrayList()
print(letterArray) // arrayListOf("a", "b", "c", "d")

Categories

Resources