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
}
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);
}
Im trying to write a program that takes a string of user inputs such as (5,6,7,8) and converts it to an arrayList of integers e.g. {5,6,7,8}. I'm having trouble figuring out my for loop. Any help would be awesome.
String userString = "";
ArrayList<Integer> userInts = new ArrayList<Integer>();
System.out.println("Enter integers seperated by commas.");
userString = in.nextLine();
for (int i = 0; i < userString.length(); i++) {
userInts.add(new Integer(in.nextInt()));
}
If your list consists of single-digit numbers, your approach could work, except you need to figure out how many digits there are in the string before allocating the result array.
If you are looking to process numbers with multiple digits, use String.split on the comma first. This would tell you how many numbers you need to allocate. After than go through the array of strings, and parse each number using Integer.parseInt method.
Note: I am intentionally not showing any code so that you wouldn't miss any fun coding this independently. It looks like you've got enough knowledge to complete this assignment by reading through the documentation.
Lets look at the lines:
String userString = ""
int[] userInt = new int[userString.length()];
At this point in time userString.length() = 0 since it doesnt contain anything so this is the same as writing int[] userInt = new int[0] your instantiating an array that cant hold anything.
Also this is an array not an arrayList. An arrayList would look like
ArrayList<Integer> myList = new ArrayList()<Integer>;
I'm assuming the in is for a Scanner.
I don't see a condition to stop. I'll assume you want to keep doing this as long as you are happy.
List<Integer> arr = new ArrayList<Integer>();
while(in.hasNext())
arr.add(in.nextInt());
And, say you know that you will get 10 numbers..
int count = 10;
while(count-- > 0)
arr.add(in.nextInt());
Might I suggest a different input format? The first line of input will consist of an integer N. The next line contains N space separated integers.
5
3 20 602 3 1
The code for accepting this input in trivial, and you can use java.util.Scanner#nextInt() method to ensure you only read valid integer values.
This approach has the added benefit of validate the input as it is entered, rather than accepting a String and having to validate and parse it. The String approach presents so many edge cases which need to be handled.
Trying to sort the doubles in descending order from my .txt file and print out the results, but why am I getting 4 lines of []?
My text file looks like this:
Mary Me,100.0
Hugh More,50.8
Jay Zee,85.0
Adam Cop,94.5
with my code that looks like this:
public static void sortGrade() throws IOException
{
Scanner input = new Scanner(new File("Grades.txt"));
while(input.hasNextLine())
{
String line = input.nextLine();
ArrayList<Double> grades = new ArrayList<Double>();
Scanner scan = new Scanner(line);
scan.useDelimiter(",");
while(scan.hasNextDouble())
{
grades.add(scan.nextDouble());
}
scan.close();
Collections.sort (grades,Collections.reverseOrder());
System.out.println(grades);
}
input.close();
}
I'd like for the output to look like this:
Hugh More,50.8
Jay Zee,85.0
Adam Cop,94.5
Mary Me,100.0
A push in the right direction would be great, thanks.
The problem is you're not reading in your values correctly!
You're reading in your line here:
String line = input.nextLine();
And then trying to parse it with a second one but this:
scan.hasNextDouble()
Will always return false as the first token in each string is the name! And it's not a double. You need to change the way you're parsing your input.
Furthermore if you want to sort both the name and the score at the same time you have to create an object that would encapsulate both name and grade and implement Comparable or write a custom Comparator for that type. Otherwise you'd have to make a Map mapping grade to each name, sort the grades and then print it in order while getting names for each grade (there can be multiple names for the same grade). This is not recommended because it does look clumsy.
Writing a comparable class really isn't that hard you just need to implement one method :-)
#Edit: you don't need a second scanner, if your format is set and that easy just use a split on that line like this:
String[] gradeName = line.split(",");
grades.add(Double.parseDouble(gradeName[1]));
If you can have more than 1 grade per person than instead of just getting gradeName[1] iterate over gradeName starting from the element at index 1 (since 0 is the name).
#Edit2:
You are creating a new grades list in the loop every time, so it will read one entry, add it to the list, sort it and print it. You should pull out everything except for those lines outside the while loop:
String line = input.nextLine();
String[] gradeName = line.split(",");
grades.add(Double.parseDouble(gradeName[1]));
#Edit3:
If you want an ascending order don't use Collections.reverseOrder(), just the default one:
Collections.sort (grades);
Imagine that you have this situation:
List<String> al = new ArrayList<>();
al.add("[I] am");
al.add("you are");
al.add("I");
al.add("[I] like java");
Now I want to count the sequence [I] (in this case it will count 2 times). The Link How to count the number of occurrences of an element in a List just pust one word, but on my example I have more than one, i.e, Collections.frequency(al, "[I]") do not work.
How can I achieve this preferentially using Java 8 ?
Another way is to split the stream by space and then check whether chunk is equal to [I] e.g.
System.out.println(al.stream().map((w) -> w.split(" ")).flatMap(Arrays::stream).filter((i) ->i.equals("[I]")).count());
Using equals have advantage over contains because let say your list contains words like below
List<String> al = new ArrayList<>();
al.add("[I] am [I]");
al.add("you are");
al.add("I");
al.add("[I] like java");
This solution will return 3 as expected but the solution mentioned by Bohuslav Burghardt will return 2
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.