Hi I'm trying to create a contacts list I have an array of contacts and I'm looping through each one and getting the first character of the last name. I'm then trying to create an array with the value of that character and add it to my final array. Then I want to check if the array already exists in my final array. If it doesn't add it to the array.
The aim being so I end up with an array list of arrays that are going to be headers in a list view. Does anyone know how to create an empty array and name it the value of a string (I'm going to add stuff to this array later)? and then add that to an array list?
Here is what I have tried so far but I'm struggling to get my head round it
for (int i=0; i<contactsJSONArray.length(); i++) {
singleContactDict = contactsJSONArray.getJSONObject(i);
Log.v("Main", "Contact singleContactDict " + i +"= " + singleContactDict);
String firstname = singleContactDict.getString("first_name");
String lastname = singleContactDict.getString("last_name");
char firstLetterInLastname = lastname.charAt(0);
Log.v("Main", "firstLetterInLastname = " + firstLetterInLastname);
headerWithLetterArray.add((firstLetterInLastname).toArray);
}
array is something like [a,b,c,d], they don't have names. If you mean JSONArray and you want to store everything is JSONObcject try:
parentJson.put(lastname.substring(0,1), new JSONArray());
You can try using "Map" for the final collection. Where your first character of the last name can be a key in the map and the real name will become value (value internally can be a arraylist).
When you want to add a new contact to list, you can first look for the key in the map with the first letter. If it is then get the value which is arraylist and add the new contact to that.
In this way you will have lots of arraylist marked by the single letter in map which can be used in loop to fill the list.
Related
I want to add a String to a specific location in an ArrayList that looks like this:
ArrayList <String[][]> arrayList3D = new ArrayList<>(Arrays.asList(arrayString3D));
I tried this out:
arrayList3D.get(0).get(1).add("new Word");
but it didn't work...
Man, first you should create an array and later the another. try this.
ArrayList<ArrayList<String>> arrayList3D = new ArrayList<ArrayList<String>>();
Later, you should create the another.
arrayList3D.add(0, new ArrayList<String>());
but you show that you want to do this.
arrayList3D.get(0).get(1).add("new Word");
The problem here is that does it exist a value in that position. It does, it works, but, it doesn't.. you should write this.
ArrayList3D.get(0).add(1, "value to input");
You're close but not quite correct.
The process goes as follows:
arrayList3D.get(0) regardless of the index provided ( 0 or greater) will return a 2D array i.e String[][].
so in order to access a particular position of the 2D array, you'll need to use 2 pairs of square brackets one indicating the row and another indicating the column.
i.e
arrayList3D.get(0)[1][0] = "new Word";
Arrays in Java don't provide get methods. An equivalent is given by bracket notation. You set the element at index i like:
array[i] = value;
Your ArrayList contains elements of type String[][] which are arrays that contain other arrays that hold String elements.
So a correct access would look like:
arrayList3D.get(0)[1][i] = "new Word";
Where i is the position you want to add the element in the last array.
Maybe this view helps more:
arrayList3D // ArrayList<String[][]>
.get(0) // String[][]
[1] // String[]
[i] // String
= "new Word";
If you want to have get methods and be able to dynamically add elements, you would need something like ArrayList<List<List<String>>> instead since arrays are of fixed size.
You could do it by manually converting your String[][][] to List<List<List<String>>>, for example by using regular loops:
List<List<List<String>>> arrayList3D = new ArrayList<>();
// Traverse all 2-dim elements
for (String[][] dim2Arr : arrayString3D) {
List<List<String>> arrayList2D = new ArrayList<>();
// Traverse all 1-dim elements
for (String[] dim1Arr : dim2Arr) {
List<String> arrayList1D = Arrays.asList(dim1Arr);
// Add 1-dim to 2-dim
arrayList2D.add(arrayList1D);
}
// Add 2-dim to 3-dim
arrayList3D.add(arrayList2D);
}
I need to check if a specific variable is in a very large array of Strings (1000+), however doing it with just a for loop and comparing each time would be slow. Is there an alternate method to the way I am using below?
String[] easyWords= new String[]{"integer","project","octopus"}; //+1000s more words
String easyrnd = (easywords[new Random().nextInt(easywords.length)]);
String letterguess = consolereader.nextLine();
for(int i=0;i<easyWords.length;i++){
if(letterguess==easywords[i]){
// do something
}
You can use easyrnd.contains(letterguess) to check if letterguess exists in easyrnd.
I have an array list like this: ArrayList names = new ArrayList<>(); that stores people's first and last names when they are entered in different textbooks.
So when prompted to Joe Biden would be element number 1 then Barack Obama would be element number 2 in the array list. My question is that if it is possible to only get their first names like Joe from the array without getting Biden also?
Yes you could just do
names.get(0).split("\\s+")[0] //this would get you "Joe"
to get last name possibly do
names.get(0).split("\\s+")[1] //this would get you "Biden"
This way completely relies on the fact that you have a space in between their first and last name. and obviously edit the 0 to whatever index you would like.
Each element will be sitting in the ArrayList as a String object.
You could use the Str.split() to split it into a array and get the last name.
Let's say your ArrayList
String str = names.get(0); //Joe Biden
String[] arr = str.split(" "); //this will create Array of String objects
System.out.println(arr[1]); will print Biden
However be careful using this method, it'll not work with people with 3 names or one name. People with one names will cause an ArrayIndexOutOfBoundsException. People with more than one name will print their last name incorrectly.
However you can overcome this by doing,
int arrLength = arr.length;
if(arrLength > 0) {
System.out.println(arr[arrLength - 1]); //this will always print the last name, if the name isn't empty
}
I'd like to know, in detail, how the Enhanced For Loop works in Java (assuming i do get how the basic usage of this loop is and how it works in general).
Given the following code:
String[] a = {"dog", "cat", "turtle"};
for (String s : a) {
out.println("String: " + s);
s = in.readLine("New String? ");
}
It doesn't actually modify the original list 'a'.
Why not? How memory Management works? Isn't 's' a reference to the same memory cell of 'a[i]'?
I read on the oracle documentation that enhanced for loops can't be used to remove elements from the original array, it makes sense. Is it the same for modifying values?
Thanks in advance
Isn't 's' a reference to the same memory cell of 'a[i]'?
Originally, yes. But then in.readLine produces a reference to a new String object, which you then use to overwrite s. But only s is overwritten, not the underlying string, nor the reference in the array.
s is a local variable that points to the String instance. It is not associated with a[i], they just happen to have the same value initially.
You can only write
for (int i = 0; i < a.length; i++) {
out.println("String: " + a[i]);
a[i] = in.readLine("New String? ");
}
You can't use for-each loops to modify the original collection or array.
Think in s like an address to an object. The thing here is that s is pointing out to a certain value of the array when using the for loop. When you reassing s inside the loop is just happen that s points out to another value but the original value of the array is not modified as you are only changing the address s is pointing to.
String[] a = {"dog", "cat", "turtle"};
for (String s : a) {
//s --> "dog"
out.println("String: " + s);
s = in.readLine("New String? ");
//s --> the new string the user inputs
}
For every iteration String s initially references to corresponding String object in String a[]. But it is then referenced to another String object that is returned by in.readLine().
Hi everyone I am having a problem trying to get this to work. Basically what I wanted to do is to read a text file containing this kind of data not exactly but just similar and count the frequency of each letter appearing on each line. Also the real data contains any random ASCII from 0-255.
An examples is:
Hi this is john.
We are going .4%2) &,.! m#ll
What I wanted to have is something like this implemented in Lists of Maps
{H=3, i=3, ' '=3, t=1, h=2, s=2,... until the end of the line },
{W=1, e=2, ' '=4, a=1, r=1, g=2, o=1, i=1, n=1, .=2, 4=1, %=1.... until the end of line},
so its a Lists of Map
I have tried to research on similar questions but the closest I can do in coding it is this.
List <Map<String, Integer>> storeListsofMaps = new ArrayList<Map<String, Integer>>();
ArrayList <String> storePerLine = new ArrayList<String>();
String getBuf;
try {
FileReader rf = new FileReader("simpleTextCharDist.txt");
BufferedReader encapRF = new BufferedReader(rf);
getBuf = encapRF.readLine();
while (getBuf!=null){
storePerLine.add(getBuf);
getBuf = encapRF.readLine();
}
for (String index: storePerLine){
Map<String, Integer> storeCharAndCount = new HashMap<String, Integer>();
Integer count = storeCharAndCount.get(index);
storeCharAndCount.put(index, (count==null)?count = 1:count+1);
storeListsofMaps.add(storeCharAndCount);
}
System.out.println("StoreListsofMaps: "+ storeListsofMaps);
encapRF.close();
}
I know this code would not execute the one I described but am stuck up until this part. The code I have shown will only count the word itself not each letter in the string. I tried counting iterating over each element in the string by converting the string into char [] and converting it back to string again, but it is very inefficient and produces alot of errors. Hope anyone would be kind enough to help.
Here is the pseudo algo to achieve this -
Using file I/O create a list containing 1 line as 1 element in the list
Write a small helper function which will:
take String (representing an element from list created in step 1)
iterate through the line
create a map of char & count. This map should be the return type.
Create a Map<String,Map<String,Int>> where 1st String is the "Line1", "Line2", etc. 2nd String is the char value. The Map written inline is the map returned from Step 2.
This should work.
Think about what you are trying to do. Write down your algorithm in text form. Think about when you have to create your variables, aqnd which types your varibales need to have. Compare your written algorithm with your actual code.
Example algorithm:
Open file
Create a list of maps of charcaters to integers (ArrayList>)
Read all lines; for each line:
Create a map char -> int for that line (HashMap)
For each character c in the line:
update the count in the map
Store the map for one line in the list of maps