typical operations on stored string in java - java

What is the Best Data Structure availaible in java to Store strings and then do some operations on it as such as:(Beginner in Java)
Input: Sam Mohit Laksh Nitesh Aquib
i know i can store each of them in data structures as such as ArrayList and etc.
But if i store them as:
Scanner sc= new Scanner(System.in);
ArrayList<String> list = new ArrayList<String>();
then iterating and adding them as:
for(int i=0;i<n;i++)
//let n be any number
{
List.add(sc.next());
}
but What if i want to Convert a Word Like Mohit to as a char array as ['M','o','h','i','t']
so that char[0]='M' or char[3]='i'
i know i can iterate through an iterator object of type MyArrayList. but can that iterator be converted to char array ?

but can that iterator be converted to char array ?
Yes Iterator#next() will give you string (because List has generic type String) that can be used to perform any kind of string operation. See the code below put it in main method and run.
String[] str = {"Sam", "Mohit", "Laksh", "Nitesh"};
List<String> list = new ArrayList<String>();
for(int i=0;i<str.length;i++)
{
list.add(str[i]);
}
Iterator<String> iter = list.iterator();
while(iter.hasNext()){
//here apply some condition to get your specific string object
char[] chars = iter.next().toCharArray();
System.out.println(chars);
}

I would propose ArrayList and streams for transforming in something else :
List<String> words = new ArrayList<>();
words.add("John");
words.add("Mohito");
Transformation List<String> to List<char[]>:
List<char[]> asChar = words.stream()
.map(String::toCharArray)
.collect(Collectors.toList());
For transforming char[] to List<Character>:
char[] cc = new char[]{'a', 'b'};
List<Character> collect1 = String.valueOf(cc)
.chars()
.mapToObj(i -> (char) i)
.collect(Collectors.toList());
Getting char from List:
String letter = collect1.get(0).toString();

Related

How to split a String("dog") to an Arraylist ['d', 'o', 'g']?

I have an input String and I want its letters to be in an ArrayList. Like "abc" to ['a', 'b', 'c'].
I've tried split() method but its error is Cannot resolve method 'asList(java.lang.String[])'
userInput = scanner.next();
inputLetters = new ArrayList<Character>(Arrays.<Character>asList(userInput.split("")));
I have java 13 so this should have work
When you pass a String[] to Arrays.asList(), you'll get a List<String>, not a List<Character>.
You can convert your List<String> to a List<Character> as follows:
List<Character> inputLetters = Arrays.asList(userInput.split(""))
.stream()
.map(s -> s.charAt(0))
.collect(Collectors.toList());
Another way to get a List<Character>:
List<Character> inputLetters = userInput.chars()
.mapToObj(i -> (char)i)
.collect(Collectors.toList());
Of course, if you don't mind working with a char[] instead of a List<Character>, simply use userInput.toCharArray().
This error is caused because userInput.split("") produces ["a","b","c"] which is a String array instead of the expected ['a','b','c'] which is a char array.
A simple workaround is:
Split string to char array
Create an empty arrayList
Iterate through char array and add it to the arrayList
String userInput = "abc";
char[] inputCharArray = userInput.toCharArray();
List<Character> userList = new ArrayList<>();
for(char c: inputCharArray)
userList.add(c);
You can use toCharArray .Here is the example code
String userInput = "abc";
for (char c : userInput.toCharArray()) {
System.out.println(c);
}
This code should work:
public static ArrayList<Character> convertStringToList(String s){
ArrayList<Character> list = new ArrayList<>();
char[] chars = s.toCharArray();
for (char c : chars){
list.add(c);
}
return list;
}
The code just converts the String to a char[] and iterates through the array, forming the list.

arraylist of character arrays java

I originally have an arraylist of strings but I want to save it as an arraylist of those strings.toCharArray() instead. Is it possible to make an arraylist that stores char arrays? Here is how I tried to implement it.
String[] words = new String[]{"peter","month","tweet", "pete", "twee", "pet", "et"};
HashMap<Integer,ArrayList<Character[]>> ordered = new HashMap<>();
int length = 0;
int max = 0; //max Length of words left
for(String word: words){
if(ordered.containsKey(length) == false){ //if int length key doesnt exist yet
ordered.put(length, new ArrayList<Character[]>()); //put key in hashmap with value of arraylist with the one value
ordered.get(length).add(word.toCharArray());
}
}
Note that toCharArray() returns an array of primitives (char[]), and not an array of the boxing class (Character[] as you currently have). Additionally, you're only adding the given array to the map if the length of the array isn't in the map, which probably isn't the behavior you wanted (i.e., you should move the line ordered.get(length).add(word.toCharArray()); outside the if statement).
Also, note that Java 8's streams can do a lot of the heavy lifting for you:
String[] words = new String[]{"peter","month","tweet", "pete", "twee", "pet", "et"};
Map<Integer, List<char[]>> ordered =
Arrays.stream(word)
.map(String::toCharArray)
.collect(Collectors.groupingBy(x -> x.length));
EDIT:
As per the question in the comment, this is also entirely possible in Java 7 without streams:
String[] words = new String[]{"peter","month","tweet", "pete", "twee", "pet", "et"};
Map<Integer, List<char[]>> ordered = new HashMap<>();
for (String word: words) {
int length = words.length();
// if int length key doesnt exist in the map already
List<char[]> list = orderd.get(length);
if (list == null) {
list = new ArrayList<>();
orderd.put(length, list);
}
list.add(word);
}

Java: Removing item from array because of character

Lets say you have an array like this: String[] theWords = {"hello", "good bye", "tomorrow"}. I want to remove/ignore all the strings in the array that have the letter 'e'. How would I go about doing that? My thinking is to go:
for (int arrPos = 0; arrPos < theWords.length; arrPos++) { //Go through the array
for (int charPos = 0; charPos < theWords[arrPos].length(); charPos++) { //Go through the strings in the array
if (!((theWords[arrPos].charAt(charPos) == 'e')) { //Finds 'e' in the strings
//Put the words that don't have any 'e' into a new array;
//This is where I'm stuck
}
}
}
I'm not sure if my logic works and if I'm even on the right track. Any responses would be helpful. Many thanks.
One easy way to filter an array is to populate an ArrayList with if in a for-each loop:
List<String> noEs = new ArrayList<>();
for (String word : theWords) {
if (!word.contains("e")) {
noEs.add(word);
}
}
Another way in Java 8 is to use Collection#removeIf:
List<String> noEs = new ArrayList<>(Arrays.asList(theWords));
noEs.removeIf(word -> word.contains("e"));
Or use Stream#filter:
String[] noEs = Arrays.stream(theWords)
.filter(word -> !word.contains("e"))
.toArray(String[]::new);
You can directly use contains() method of String class to check if "e" is present in your string. That will save your extra for loop.
It would be simple if you use ArrayList.
importing import java.util.ArrayList;
ArrayList<String> theWords = new ArrayList<String>();
ArrayList<String> yourNewArray = new ArrayList<String>;//Initializing you new array
theWords.add("hello");
theWords.add("good bye");
theWords.add("tommorow");
for (int arrPos = 0; arrPos < theWords.size(); arrPos++) { //Go through the array
if(!theWords.get(arrPos).contains("e")){
yourNewArray.add(theWords.get(arrPos));// Adding non-e containing string into your new array
}
}
The problem you have is that you need to declare and instantiate the String array before you even know how many elements are going to be in it (since you wouldn't know how many strings would not contain 'e' before going through the loop).
Instead, if you use an ArrayList you do not need to know the required size beforehand. Here is my code from start to end.
String[] theWords = { "hello", "good bye", "tomorrow" };
//creating a new ArrayList object
ArrayList<String> myList = new ArrayList<String>();
//adding the corresponding array contents to the list.
//myList and theWords point to different locations in the memory.
for(String str : theWords) {
myList.add(str);
}
//create a new list containing the items you want to remove
ArrayList<String> removeFromList = new ArrayList<>();
for(String str : myList) {
if(str.contains("e")) {
removeFromList.add(str);
}
}
//now remove those items from the list
myList.removeAll(removeFromList);
//create a new Array based on the size of the list when the strings containing e is removed
//theWords now refers to this new Array.
theWords = new String[myList.size()];
//convert the list to the array
myList.toArray(theWords);
//now theWords array contains only the string(s) not containing 'e'
System.out.println(Arrays.toString(theWords));

Filter Java list and create integer constants array

I have a Java list of Strings as below:
myList:
C26366
C10025, C10026
C10244
C26595
C26594
C9026, C9027, C9029, C9080 //this is one list element (needs seperation)
C26597
C10223, C10287, C10277, C10215
C10242
C10243
C9025, C9030, C9034, C9051, C9052, C9055 // similarly here
C10241
C10067
C27557
C10066
.... //these are all ids
Above is an output of below for-loop snippet:
for (String id: myList) {
System.out.println(id);
}
How do I convert this myList into a Java integer array? I am expecting something like/I want to use use that array as:
public static final IDS = { 31598,9089,9092,9093,9108,9109,....}
IDS array must hold the content from myList and they are without any C's in them and no other characters, but just the numbers.
In Java 8 you can use streams:
List<String> myList = Arrays.asList(
"C26366", "C10025, C10026", "C10244", "C26595", "C26594",
"C9026, C9027, C9029, C9080", "C26597", "C10223, C10287, C10277, C10215",
"C10242", "C10243",
"C9025, C9030, C9034, C9051, C9052, C9055", "C10241", "C10067");
List<Integer> myListOfIntegers = myList.stream()
.map(x -> x.split(","))
.flatMap(l -> Arrays.asList(l).stream())
.map(y -> y.replaceAll("\\D", ""))
.map(z->Integer.parseInt(z))
.collect(Collectors.toList());
for( Integer i : myListOfIntegers ){
System.out.println(i);
}
a result is:
26366
10025
10026
10244
26595
26594
9026
9027
9029
9080
26597
10223
10287
10277
10215
10242
10243
9025
9030
9034
9051
9052
9055
10241
10067
I would suggest to do this:
Define a list of integers for the final values
then use Regex with this pattern "\d+" to find in the list of strings only the things that are numeric
if found, parse it to integer and add it to the list.
Example:
List<Integer> myListIntegers = new ArrayList<Integer>();
for (String subStrings : myList) {
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(subStrings);
while (m.find()) {
myListIntegers.add(Integer.parseInt(m.group()));
}
}
System.out.println(myListIntegers);
this code will print the list holding the insteger you have in myList
[26366, 10025, 10026, 10244, 26595, 26594, 9026, 9027, 9029, 9080,
10241, 10067, 27557, 10066]

Remove String from list if certain character missing

I have a list of words ["home", "shop", "salmon", "time"] and I have a scrambled String "ahlowemr". I want to check if each word in the list has characters from this scrambled String and remove the word from list if it doesn't contain all the characters.
In this example, less "home", the remaining 3 Strings should be removed. I tried to loop as follows but it doesn't allow me to check characters. And I am nesting loops which I think is not a good idea. Is there any way around this?
ArrayList<String> myList = new ArrayList<String>();
myList.add("home");
myList.add("shop");
myList.add("salmon");
myList.add("time");
String scrambled = "ahlowemr";
for(String s : myList){
for(char c : scrambled.toCharArray()){
if(!s.contains(c)){ //doesn't allow character c
myList.remove(s);
}
}
}
If you want to remove items from a list while you iterate it, you should use an Iterator, also, the contains(...) method expects a String, not a char.
Here is what you can do:
for(Iterator<String> it = myList.iterator(); it.hasNext();){
String s = it.next();
for(char c : scrambled.toCharArray()){
if(!s.contains(String.valueOf(c))){
it.remove();
break;
}
}
}
ArrayList<String> myList = new ArrayList<String>();
myList.add("home");
myList.add("shop");
myList.add("salmon");
myList.add("time");
String scrambled = "ahlowemr";
for(int i = 0; i < myList.size(); i++) {
for(char c : scrambled.toCharArray()){
if(!myList.get(i).contains(c.toString())){ //doesn't allow character in that position
// There is a simple way using a regex or maybe a hashtable
myList.remove(s);
break; // break will jump into the next list value
}
}
}
java-8 solution for completeness:
ArrayList<String> myList = new ArrayList<>();
myList.add("home");
myList.add("shop");
myList.add("salmon");
myList.add("time");
String scrambled = "ahlowemr";
myList = myList.stream()
.filter(s -> scrambled.chars()
.allMatch(c -> s.contains(String.valueOf((char) c))))
.collect(Collectors.toCollection(ArrayList<String>::new));

Categories