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
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.
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 have a dictionary.txt which has many vocab. I want to sort those vocab according to their word length. For that, I intend to create a Set for each particular word length, and put words with that length into that set.
I have thought of creating many sets by myself, ie. creating sets:
Set<String> wordLength1 = new TreeSet<String>();
Set<String> wordLength2 = new TreeSet<String>();
Set<String> wordLength3 = ...;
but it is too clumsy to do it - I may have to create at least twenty to thirty sets.
What's more, I dont know what is the maximum number of length of a word (I dont wanna scan the whole dictionary.txt first in order to get the maximum word length... a bit clumsy). Is there a way that is: to create a new set only if I find that the word length correspond to a set that I have not created before. eg. if the input word has a length of 7, and I find that I have not created a set called wordLength7, then I create it; else I just simply put it into that set.
And is there a method to put a word into a set besides the following clumsy method?
if (word.length() == 1) {
wordLength1.add(word);
} else if (word.length() == 2) {
wordLength2.add(word);
} else if (word.length() == 3) {
wordLength3.add(word);
} else if ...
Create a Map that maps the length to the set of words.
Map<Integer, Set<String>> lengthToWords = new HashMap<Integer, Set<String>>();
and fill it like this
Set<String> words = lengthToWords.get(word.length());
if(words == null) {
words = new TreeSet<String>();
lengthToWords.put(word.length(), words);
}
words.add(word);
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