length of each element in an array Java - java

Here is what I'm trying to use. The method .length doesn't work for anything I try, so I'm not even sure where to begin.
import java.util.ArrayList;
public class LengthsOfStrings {
public static ArrayList<Integer> lengths(ArrayList<String> list) {
ArrayList<Integer> lengthList = new ArrayList<Integer>();
for (int nums: lengthList) {
System.out.println(nums.length());
}
return lengthList;
}
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("Ciao");
list.add("Moi");
list.add("Benvenuto!");
list.add("badger badger badger badger");
ArrayList<Integer> lengths = lengths(list);
System.out.println("The lengths of the Strings: " + lengths);
}
}

You are trying to iterate through a single int instead of the strings array. Change
for (int nums: lengthList) {
System.out.println(nums.length());
}
to
for (String str: list) { // loop through the list of strings
lengthList.add(str.length()); // store the individual length of each string
}
so as to loop through the list of strings, collect the length of each string & store it int the Arraylist that you return later.

In the following code:
ArrayList<Integer> lengthList = new ArrayList<Integer>();
for (int nums: lengthList) {
System.out.println(nums.length());
}
You are creating an ArrayList<Integer> lengthList which is empty and trying to iterate over it.
I think you want to iterate over list something like this:
for (String s: list) {
lengthList.add(s.length());
System.out.println(s.length());
}
and add length() of each String to lengthList in each iteration.

Here in your code you need to update at 2 places:
1) In lengths method you are passing list(ArrayList<String> list), but you are not iterating over that you. You have to iterate over this list.
2) In the for loop you have made the variable as int, while the list is of type String. So update your code like below :
public static ArrayList<Integer> lengths(ArrayList<String> list) {
for (String nums: list) {
System.out.println(nums.length());
}
return lengthList;
}

For Java 8 user
public static void main(final String[] args) {
List<String> strings = Arrays.asList("Hi", "Hello", "how r u?");
List<Integer> lengthList = lengths(strings);
lengthList.forEach(System.out::println);
}
public static List<Integer> lengths(List<String> list) {
return list.stream().mapToInt(s -> s.length()).boxed()
.collect(Collectors.toList());
//OR
return list.stream().mapToInt(String::length).boxed()
.collect(Collectors.toList());
}

Related

Anagrams finding in java

I stuck on a problem. I have a String array which is consist of String[]={"eat", "tea", "tan", "ate", "nat", "bat"} Now, I should segregated those word which have same letter on it and make a group. eat,tea,ate they have same letter in each word so this is a group. Group 2 should be tan,nat and Group3 should be bat. So I have to make a list of list to store those groups.
My approach:
To solve this problem I first find out the ascii values of each letter and then add those ascii values for a word. Like eat find out the ascii values of e,a,t and add them. I take this approach because if the letters are repeated in the words then they must have same ascii sum. After that I group them same Ascii sums and find out which words have those sums then they belongs to same group.
My progress
I find out ascii sums and put them in a hashmap. But then I could not group the same values. As I failed to group the ascii values I cannot find out the words.I have no clue how to proceed.
I also follow this posts
post1
post2
But there approach and my approach is not same. Also the questions are different from mine. I am discussing here about a different approach which is depend upon ASCII values.
My code:
public List<List<String>> groupAnagrams(String[] strs) {
ArrayList<Character>indivistr=new ArrayList<>();
ArrayList<Integer>dup=new ArrayList<>();
HashMap<Integer,Integer>mappingvalues=new HashMap<>();
for(int i=0;i<strs.length;i++){
int len=strs[i].length();
int sum=0;
for(int j=0;j<len;j++){
indivistr.add(strs[i].charAt(j));
int ascii=(int)strs[i].charAt(j);
sum=sum+ascii;
}
mappingvalues.put(i,sum);
}
}
One more approach
I transfer the map keys in a Arraylist and map values in a ArrayList. Something like that,
ArrayList<Integer>key_con=new ArrayList<
(mappingvalues.keySet());
ArrayList<Integer>val_con=new ArrayList<>(mappingvalues.values());
Then using two loops and put the same values into another list.
for(int k=0;k<val_con.size();k++){
for(int k1=k+1;k1<val_con.size();k1++){
if(val_con.get(k).equals(val_con.get(k1))){
dup.add(val_con.get(k1));
}
}
Now if I print dup output will be [314, 314, 314, 323] which is partially correct. It should be 314,314,314,323,323,311
This should get you started.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Main {
public static void main(String args[]) throws Exception {
String[] words ={"eat", "tea", "tan", "ate", "nat", "bat"};
for(List<String> list : groupAnagrams(words))
System.out.println(list);
}
public static List<ArrayList<String>> groupAnagrams(String[] words) {
List<ArrayList<String>> wordGroups = new ArrayList<ArrayList<String>>();
HashMap<Integer, ArrayList<String>> map = new HashMap<Integer, ArrayList<String>>();
for(String word : words) {
int sum = 0;
for(char c : word.toCharArray())
sum += c;
if(map.containsKey(sum))
map.get(sum).add(word);
else {
ArrayList<String> list = new ArrayList<String>();
list.add(word);
map.put(sum, list);
}
}
for(ArrayList<String> list : map.values())
wordGroups.add(list);
return wordGroups;
}
}
This program will work for small scale things such as this but consider the following input data:
{"a", "#!"}
The sum of these Strings are both 97.
Since you're using ASCII values to find anagrams you might run into a case such as this. This isn't a particularly pressing matter until you start messing around with lowercase letters and capitals. Easy fix for that is just a String.ToUpperCase() and map the symbols to huge numbers and you're good to go.
For posterity:
public class anagrams {
public static void main(String args[]) {
int numberOfAnagrams = 0;
String[] stringArray = {"eat", "tea", "tan", "ate", "nat", "bat", "plate", "knot"};
List<String> stringList = Arrays.asList(stringArray);
for(int i = 0; i < stringList.size() - 1; i++) {
for(int j = i + 1; j < stringList.size(); j++) {
if(isAnagram(stringList.get(i), stringList.get(j))) {
System.out.println(stringList.get(i) + " " + stringList.get(j));
numberOfAnagrams += 2;
}
}
}
System.out.println(numberOfAnagrams);
}
private static boolean isAnagram(String s1, String s2) {
// In order for two String to be anagrams, they must have the same length.
if(s1.length() != s2.length()) {
return false;
}
// If s2 does not contain even one of s1's chars return false.
for(int i = 0; i < s1.length(); i++) {
if(!s2.contains("" + s1.charAt(i))) {
return false;
}
}
return true;
}
}
Based on the asci approach I have made a working code
public static void main(String[] args) {
String[] values ={"eat", "tea", "tan", "ate", "nat", "bat"};
Map<Integer, List<String>> resultMap = new HashMap<Integer, List<String>>();
for (String value : values) {
char[] caharacters = value.toLowerCase().toCharArray();
int asciSum = 0;
for (char character : caharacters) {
asciSum = asciSum + (int)character;
}
System.out.println(asciSum);
if(resultMap.containsKey(asciSum)) {
resultMap.get(asciSum).add(value);
}else {
List<String> list = new ArrayList<String>();
list.add(value);
resultMap.put(asciSum, list);
}
}
System.out.println(resultMap);
}
This will give result
{323=[tan, nat], 311=[bat], 314=[eat, tea, ate]}
but if we encounter diff characters with same asci value sum like 10+11 = 20+1
below code will work where based on the sorted string we make the result map
public static void main(String[] args) {
String[] values ={"eat", "tea", "tan", "ate", "nat", "bat"};
Map<String, List<String>> resultMap = new HashMap<String, List<String>>();
for (String value : values) {
char[] caharacters = value.toLowerCase().toCharArray();
Arrays.sort(caharacters);
String sortedValue = new String(caharacters);
System.out.println(sortedValue);
if(resultMap.containsKey(sortedValue)) {
resultMap.get(sortedValue).add(value);
}else {
List<String> list = new ArrayList<String>();
list.add(value);
resultMap.put(sortedValue, list);
}
}
System.out.println(resultMap);
}
This will return
{aet=[eat, tea, ate], abt=[bat], ant=[tan, nat]}
I have fixed the comments and edits provided.
Here's my idea, first I would create a class that will store the original string and it's sorted version:
class Anagram {
String s;
String sorted;
}
Then I map the input to my list of Anagram:
List<Anagram> collect = Arrays.stream(strs)
.map(a -> new Anagram(a, Arrays.stream(a.split(""))
.sorted()
.reduce(String::concat).get()))
.collect(Collectors.toList());
Then I just group the obtained list by sorted string:
Map<String, List<Anagram>> groupBy = collect
.stream()
.collect(Collectors.groupingBy(Anagram::getSorted));
Now you have the lists with grouped anagrams, just extract from them the original string:
List<List<String>> result = new ArrayList<>();
for(List<Anagram> list : collect1.values()) {
List<String> myList = list.stream().map(Anagram::getS).collect(Collectors.toList());
result.add(myList);
}

Split ArrayList of Strings into another ArrayList of Strings with the return type being a List, and not void

My code is supposed to return an Arraylist of words when given another Arraylist of strings.
For example:
Input:
["Hello there"]
Output:
["Hello","there"]
So far I have:
public static List<String> stringToListOfWords(List<String> list )
{
for(int i = 0; i <= list.size() - 1; i++)
{
String[] temp = (list.get(i).split("\\s+"));
ArrayList<String> wordList = new ArrayList<String>(Arrays.asList(temp));
}
return(wordList);
}
I've tried moving the wordList in the for loop but then I get the error saying that the return type is wrong. I got it to work for when the return type is void but I need it to return as a list.
Any help would be great!
You should create a single ArrayList before the loop and add to it all the words inside the loop:
public static List<String> stringToListOfWords(List<String> list )
{
List<String> wordList = new ArrayList<> ();
for(int i = 0; i <= list.size() - 1; i++) {
String[] temp = list.get(i).split("\\s+");
wordList.addAll(Arrays.asList(temp));
}
return wordList;
}
You can consider using streams as of Java 8:
public static List<String> stringToListOfWords(List<String> list){
return list.stream()
.flatMap(s -> Arrays.asList(s.split("\\s+")).stream())
.collect(Collectors.toList());
}
If you are using Java 8 you can drop the loop and use a forEach instead
public static List<String> stringToListOfWords(List<String> list) {
List<String> wordList = new ArrayList<>();
list.forEach(item->{
String[] temp = item.split("\\s+");
wordList.addAll(Arrays.asList(temp));
});
return wordList;
}
or if you want to use Streams here's a one liner
public static List<String> stringToListOfWords(List<String> list) {
return list.stream()
.map(word -> word.split("\\s+"))
.flatMap(Arrays::stream)
.collect(Collectors.toList());
}

Count the number of occurrences of keywords in an Array list

public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
String s = "nope";
String v = "nopenopes";
list.add(s);
list.add(v);
keywordCount(list, "nope");
}
public static int keywordCount(ArrayList<String> str , String keyword){
int count = 0;
for (int i = 0;i<str.size();i++){
while ((i= str.indexOf(keyword,i)) != -1) { // here is where I found the error
count++;
i += keyword.length();
}}
System.out.println(count);
return count;
}
hello, I'm writing a piece of code that counts the occurrences of a specific keyword inside an array list. It worked for a line of string but did not when trying to do the same thing for an arraylist. Can someone please point out what I did incorrectly and help me fix it. Thanks in advance.
You can sue Collections.frequncy()
List<String> list=new ArrayList<>();
list.add("a");
list.add("b");
list.add("a");
System.out.println(Collections.frequency(list,"a")); // out put is 2
Let's say you have a List<String> list then you want to find number of occurrence keyword
Then
int numOfOccurrences= Collections.frequency(list,keyword)
Easily you can use contains() method;
public static int keywordCount(ArrayList<String> str , String keyword){
int count = 0;
for (int i = 0; i<str.size();i++){
if(str.get(i).contains(keyword))
count++;
}
}
You could use Arrays.asList() to construct your List.
public static void main(String[] args) {
System.out.println(keywordCount(Arrays.asList("nope", "nopenopes"), "nope"));
}
public static int keywordCount(List<String> al, String keyword) {
int count = 0;
for (String str : al) {
int i = 0;
while ((i = str.indexOf(keyword, i)) != -1) {
count++;
i += keyword.length();
}
}
return count;
}
When I run the above I get the output
3
One issue in your code was
i = str.indexOf(keyword,i)
In your post str is not a String, it is an ArrayList.
use code below.
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("a");
// get all Unique keywords
Set<String> set = new HashSet<String>(list);
for(String keyword: set){
System.out.println(keyword + ": " + Collections.frequency(list, keyword));
}
}
Output:
b: 1
a: 2

printing elements of array in arraylist in java

I do have this code, and I would like to print out all the array's values of Arraylist.
thanks for your help in advanced.
here is my code:
for (int i = 0; i <count; i++) {
System.out.println("list #" + i);
for (int j = 0; j < list[i].size(); j++) {
list[i].get(j);
System.out.println("elements of array in arraylist "+list[i].get(j));
}
}
For printing elements of an array stored in arraylist,you will have to to do the following:
for each element of arraylist
get array from arraylist
for each array element in array
print array element.
You seemed to be iterating array of List type instead.
Edit your code with further detail on your data structure
for (Object[] array : list)
for (Object o : array)
System.out.println("item: " + o);
See if this can work for you. I think it's simpler:
int numLists = 10; // Or whatever number you need it to be.
ArrayList [] arrayOfLists = new ArrayList[numLists];
// you realize, of course, that you have to create and add those lists to the array.
for (ArrayList list : arrayOfLists) {
System.out.println(list);
}
I'd wonder why you don't prefer a List of Lists:
List<List<String>> listOfLists = new ArrayList<List<String>>();
// add some lists of Strings
for (List<String> list : listOfLists) {
System.out.println(list);
}
Below code works fine for me
public class Solution
{
public static void main(String[] args)
{
int T,N,i,j,k=0,Element_to_be_added_to_the_array;
Scanner sn=new Scanner(System.in);
T=sn.nextInt();
ArrayList<Integer>[] arr=new ArrayList[T];
for(i=0;i<T;i++)
{
arr[k]=new ArrayList<Integer>();
N=sn.nextInt();
for(j=0;j<N;j++)
{
Element_to_be_added_to_the_array=sn.nextInt();
arr[k].add(Element_to_be_added_to_the_array);
}
k++;
}
//Printing elements of all the arrays contained within an arraylist
for(i=0;i<T;i++)
{
System.out.println("array["+i+"]");
for(j=0;j<arr[i].size();j++)
{
System.out.println(arr[i].get(j));
}
}
}
}

Converting ArrayList to Array in java

I have an ArrayList with values like "abcd#xyz" and "mnop#qrs". I want to convert it into an Array and then split it with # as delimiter and have abcd,mnop in an array and xyz,qrs in another array. I tried the following code:
String dsf[] = new String[al.size()];
for(int i =0;i<al.size();i++){
dsf[i] = al.get(i);
}
But it failed saying "Ljava.lang.String;#57ba57ba"
You don't need to reinvent the wheel, here's the toArray() method:
String []dsf = new String[al.size()];
al.toArray(dsf);
List<String> list=new ArrayList<String>();
list.add("sravan");
list.add("vasu");
list.add("raki");
String names[]=list.toArray(new String[list.size()])
List<String> list=new ArrayList<String>();
list.add("sravan");
list.add("vasu");
list.add("raki");
String names[]=list.toArray(new String[0]);
if you see the last line (new String[0]), you don't have to give the size, there are time when we don't know the length of the list, so to start with giving it as 0 , the constructed array will resize.
import java.util.*;
public class arrayList {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
ArrayList<String > x=new ArrayList<>();
//inserting element
x.add(sc.next());
x.add(sc.next());
x.add(sc.next());
x.add(sc.next());
x.add(sc.next());
//to show element
System.out.println(x);
//converting arraylist to stringarray
String[]a=x.toArray(new String[x.size()]);
for(String s:a)
System.out.print(s+" ");
}
}
String[] values = new String[arrayList.size()];
for (int i = 0; i < arrayList.size(); i++) {
values[i] = arrayList.get(i).type;
}
What you did with the iteration is not wrong from what I can make of it based on the question. It gives you a valid array of String objects. Like mentioned in another answer it is however easier to use the toArray() method available for the ArrayList object => http://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html#toArray%28%29
Just a side note. If you would iterate your dsf array properly and print each element on its own you would get valid output. Like this:
for(String str : dsf){
System.out.println(str);
}
What you probably tried to do was print the complete Array object at once since that would give an object memory address like you got in your question. If you see that kind of output you need to provide a toString() method for the object you're printing.
package com.v4common.shared.beans.audittrail;
import java.util.ArrayList;
import java.util.List;
public class test1 {
public static void main(String arg[]){
List<String> list = new ArrayList<String>();
list.add("abcd#xyz");
list.add("mnop#qrs");
Object[] s = list.toArray();
String[] s1= new String[list.size()];
String[] s2= new String[list.size()];
for(int i=0;i<s.length;i++){
if(s[i] instanceof String){
String temp = (String)s[i];
if(temp.contains("#")){
String[] tempString = temp.split("#");
for(int j=0;j<tempString.length;j++) {
s1[i] = tempString[0];
s2[i] = tempString[1];
}
}
}
}
System.out.println(s1.length);
System.out.println(s2.length);
System.out.println(s1[0]);
System.out.println(s1[1]);
}
}
Here is the solution for you given scenario -
List<String>ls = new ArrayList<String>();
ls.add("dfsa#FSDfsd");
ls.add("dfsdaor#ooiui");
String[] firstArray = new String[ls.size()];
firstArray =ls.toArray(firstArray);
String[] secondArray = new String[ls.size()];
for(int i=0;i<ls.size();i++){
secondArray[i]=firstArray[i].split("#")[0];
firstArray[i]=firstArray[i].split("#")[1];
}
This is the right answer you want and this solution i have run my self on netbeans
ArrayList a=new ArrayList();
a.add(1);
a.add(3);
a.add(4);
a.add(5);
a.add(8);
a.add(12);
int b[]= new int [6];
Integer m[] = new Integer[a.size()];//***Very important conversion to array*****
m=(Integer[]) a.toArray(m);
for(int i=0;i<a.size();i++)
{
b[i]=m[i];
System.out.println(b[i]);
}
System.out.println(a.size());
This can be done using stream:
List<String> stringList = Arrays.asList("abc#bcd", "mno#pqr");
List<String[]> objects = stringList.stream()
.map(s -> s.split("#"))
.collect(Collectors.toList());
The return value would be arrays of split string.
This avoids converting the arraylist to an array and performing the operation.
NameOfArray.toArray(new String[0])
This will convert ArrayList to Array in java
// A Java program to convert an ArrayList to arr[]
import java.io.*;
import java.util.List;
import java.util.ArrayList;
class Main {
public static void main(String[] args)
{
List<Integer> al = new ArrayList<Integer>();
al.add(10);
al.add(20);
al.add(30);
al.add(40);
Integer[] arr = new Integer[al.size()];
arr = al.toArray(arr);
for (Integer x : arr)
System.out.print(x + " ");
}
}

Categories