Java ArrayList strings lengths printing - java

My excercise is:
Create the method lengths that gets a list of String variables as a parameter and returns an ArrayList that contains the lengths of the Strings in the same order as the original list.
And my code:
import java.util.ArrayList;
public class Test {
public static ArrayList<Integer> lengths(ArrayList<String> strings) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (String item : strings) {
System.out.print(item.length());
}
return list;
}
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("Dog");
list.add("Elephant");
list.add("Aligator");
list.add("Parrot");
ArrayList<Integer> stringLenghts = lengths(list);
System.out.println(stringLenghts);
}
}
And this program outputs
3386[]
Instead of
[3, 3, 8, 6]
Any idea where I do a mistake?

In your lengths() method, you are simply printing the length values.
But you are NOT adding the lengths to the ArrayList i.e., your stringLenghts list is empty (so printing as [] empty array), so change your code as shown below:
public static ArrayList<Integer> lengths(ArrayList<String> strings) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (String item : strings) {
list.add(item.length());//add length to list
}
return list;
}

Try this.
import java.util.ArrayList;
public class Test {
public static ArrayList<Integer> lengths(ArrayList<String> strings) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (String item : strings) {
list.add(item.length());
}
return list;
}
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("Dog");
list.add("Elephant");
list.add("Aligator");
list.add("Parrot");
ArrayList<Integer> stringLenghts = lengths(list);
System.out.println(stringLenghts);
}
}
EDIT: In the lengths method, the list is being created but you are not adding any items to it. Now in the code abode for (String item : strings) { list.add(item.length()); } This adds the length of each string to the new ArrayList which you will return to the main method for printing.
Thanks

You need correct this body of cycle and add here the numbers
list.add(item.length());
between brackets.

Initially you are printing the length of each string from the loop
for(String item : strings) {
System.out.print(item.length());
}
which outputs : 3386 (no new line because of print)
After this empty ArrayList is printed because you are returning the empty arrayList object.
System.out.println(stringLenghts);
which outputs : [ ]
Solution :
You have to replace System.out.print(item.length());
with
list.add(item.length());

Related

Split a List of Strings based on value in Java

What I want to do is to split an array of strings, when the first 6 characters in the string are zeroes ("000000") or when all the digits in the string are zeroes. Limiting to 6 characters won't be very dynamic.
I got this code, and it does what I want to achieve.
import java.util.*;
public class Main
{
public static void main(String[] args) {
ArrayList<String> unsplitted = new ArrayList<String>();
unsplitted.add("000000: this_should_go_into_first_array");
unsplitted.add("000234: something1");
unsplitted.add("0000ff: something2");
unsplitted.add("000111: something3");
unsplitted.add("000051: something4");
unsplitted.add("007543: something5");
unsplitted.add("000000: and_this_should_go_into_second_array");
unsplitted.add("005612: something7");
unsplitted.add("005712: something8");
System.out.println("Unsplitted list: "+ unsplitted);
List<String> arrlist1 = unsplitted.subList(0, 6);
List<String> arrlist2 = unsplitted.subList(6, unsplitted.size());
System.out.println("Sublist of arrlist1: "+ arrlist1);
System.out.println("Sublist of arrlist2: "+ arrlist2);
}
}
Which prints out the wanted results
Sublist of arrlist1: [000000: this_should_go_into_first_array, 000234: something1, 0000ff: something2, 000111: something3, 000051: something4, 007543: somethi
ng5]
Sublist of arrlist2: [000000: and_this_should_go_into_second_array, 005612: something7, 005712: something8]
However, I don't know the indexes for the zeroes beforehand, so how can I achieve the same result by finding the zeroes dynamically?
You can simply iterate in your array and create "bucket" each time you detect your 000000 string :
ArrayList<String> unsplitted = new ArrayList<String>();
unsplitted.add("000000: this_should_go_into_first_array");
unsplitted.add("000234: something1");
unsplitted.add("0000ff: something2");
unsplitted.add("000111: something3");
unsplitted.add("000051: something4");
unsplitted.add("007543: something5");
unsplitted.add("000000: and_this_should_go_into_second_array");
unsplitted.add("005612: something7");
unsplitted.add("005712: something8");
List<List<String>> results = new ArrayList<>();
unsplitted.forEach(w -> {
if(w.startsWith("000000") || results.isEmpty()) {
// no bucket or detect 000000
List<String> bucket = new ArrayList<>();
bucket.add(w);
results.add(bucket);
}
else {
// not contains 00000 put the value in the last bucket
results.get(results.size() - 1).add(w);
}
});
results.forEach(w -> {
System.out.println("Sublist " + w);
});
Is it the result that you expected ?
The result :
Sublist [000000: this_should_go_into_first_array, 000234: something1, 0000ff: something2, 000111: something3, 000051: something4, 007543: something5]
Sublist [000000: and_this_should_go_into_second_array, 005612: something7, 005712: something8]
The question is quite interesting. There are different way to implement this, but I am going to show you a solution where it can be applied with any length of the first part, which we can consider as a key.
As you said in your introduction, it wouldn't be dynamic if the check was limited to only 6 characters. Based on this, as an example, you can take the position of the character ':' as reference and apply a partitioning among the elements of the array.
Here is the solution I propose:
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class Main
{
public static void main(String[] args) {
ArrayList<String> unsplitted = new ArrayList<String>();
unsplitted.add("000000: this_should_go_into_first_array");
unsplitted.add("000234: something1");
unsplitted.add("0000ff: something2");
unsplitted.add("000111: something3");
unsplitted.add("000051: something4");
unsplitted.add("007543: something5");
unsplitted.add("000000: and_this_should_go_into_second_array");
unsplitted.add("005612: something7");
unsplitted.add("005712: something8");
System.out.println("Non-split list: "+ unsplitted);
Predicate<String> filter = (String s) -> {
int indexOfCol = s.indexOf(":");
return s.substring(0, indexOfCol).equals("0".repeat(indexOfCol));
};
Map<Boolean, List<String>> splitMap = unsplitted.stream()
.collect(Collectors.partitioningBy(filter));
List<String> arrayZeroStart = splitMap.get(true);
List<String> arrayNonZeroStart = splitMap.get(false);
System.out.println("Sublist of arrayZeroStart: "+ arrayZeroStart);
System.out.println("Sublist of arrayWithout: "+ arrayNonZeroStart);
}
}
And here is the output:
Non-split list: [000000: this_should_go_into_first_array, 000234: something1, 0000ff:
something2, 000111: something3, 000051: something4, 007543: something5, 000000: and_this_should_go_into_second_array, 005612: something7, 005712: something8]
Sublist of arrayZeroStart: [000000: this_should_go_into_first_array, 000000: and_this_should_go_into_second_array]
Sublist of arrayWithout: [000234: something1, 0000ff: something2, 000111: something3, 000051: something4, 007543: something5, 005612: something7, 005712: something8]

Overloading same method to print different data type arraylist

My task is to overload the same method, to be able to use the same method name, to print to screen, the contents of the both array list contents.
Below is my code I have tried. But it's not working because both methods have same name?
import java.util.ArrayList;
public class Tutotrial_2_1 {
public static void main(String[] args){
//Creating integer type array list
ArrayList<Integer>listOfAges = new ArrayList<Integer>();
//Adding items to array list
listOfAges.add(25);
listOfAges.add(36);
listOfAges.add(45);
listOfAges.add(67);
listOfAges.add(87);
listOfAges.add(32);
listOfAges.add(33);
listOfAges.add(45);
//Creating double type array list
ArrayList<Double>listOfMarks = new ArrayList<Double>();
//Adding items to array list
listOfMarks.add(25.4);
listOfMarks.add(36.5);
listOfMarks.add(4.45);
listOfMarks.add(55.67);
listOfMarks.add(55.7);
listOfMarks.add(32.0);
listOfMarks.add(33.0);
listOfMarks.add(45.0);
//Calling display function of integer array
displayArray(listOfAges);
displayArray(listOfMarks);
}
//Display fucntion of listOfAges array
public static void displayArray(ArrayList<Integer>list){
for(Integer indexes : list){
System.out.println(indexes);
}
}
public static void displayArray(ArrayList<Double>list){
for(Double indexes : list){
System.out.println(indexes);
}
}
}
Due to Java's type erasure you can't overload a method over a generic type. In other words, you have two methods that resolve to displayArray(ArrayList), so you'll get a compilation error for a doubly declared method.
Luckily, you don't really need an overloaded method here - since any object in Java has a toString method, you can just have one method that receives a list, iterates over it, and print each item:
public static void displayArray(List<?> list){
for (Object indexes : list) {
System.out.println(indexes);
}
}
If I understand your problem if you change your method like this:
public static void main(String[] args) {
//Creating integer type array list
ArrayList<Integer> listOfAges = new ArrayList<Integer>();
//Adding items to array list
listOfAges.add(25);
listOfAges.add(36);
listOfAges.add(45);
listOfAges.add(67);
listOfAges.add(87);
listOfAges.add(32);
listOfAges.add(33);
listOfAges.add(45);
//Creating double type array list
ArrayList<Double>listOfMarks = new ArrayList<Double>();
//Adding items to array list
listOfMarks.add(25.4);
listOfMarks.add(36.5);
listOfMarks.add(4.45);
listOfMarks.add(55.67);
listOfMarks.add(55.7);
listOfMarks.add(32.0);
listOfMarks.add(33.0);
listOfMarks.add(45.0);
//Calling display function of integer array
displayArray(listOfAges);
displayArray(listOfMarks);
}
//Display function of listOfAges array
public static <T> void displayArray(ArrayList<T>list){
for(T indexes : list){
System.out.println(indexes);
}
}
It should work. The is use as a generic type.

Concurrent Modification Exception while adding elements to ArrayList recursively

Getting Concurrent Modification Exception while adding elements to ArrayList recursively.
import java.util.*;
public class Hello {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
String str = sc.next();
System.out.println(gss(str));
}
public static ArrayList<String> gss(String str) {
if(str.length() == 0){
ArrayList<String> list = new ArrayList<String>();
list.add("");
return list;
}
ArrayList<String> list = gss(str.substring(1));
for(String temp : list){
list.add(str.charAt(0)+temp); // Problem
}
return list;
}
}
Solution: To just form new ArrayList at each call stack and return it.
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
String str = sc.next();
System.out.println(gss(str));
}
public static ArrayList<String> gss(String str) {
if(str.length() == 0){
ArrayList<String> list = new ArrayList<String>();
list.add("");
return list;
}
ArrayList<String> list = gss(str.substring(1));
ArrayList<String> listToReturn = new ArrayList<>();
for(String temp : list){
listToReturn.add(temp);
}
for(String temp : list){
listToReturn.add(str.charAt(0) + temp);
}
return listToReturn;
}
}
I have recently come across this blog.
Which says, It uses a transient variable called modCount, which keeps track of how many times a list is modified structurally. Structural modifications are those that change the size of the list, which may affect the progress of iteration and may yield incorrect results. Both Iterator and ListIterator uses this field to detect unexpected change. Other methods of List which structurally modify List also uses this method e.g. add(), remove().
Cause: The real cause of ConcurrentModficationException is inconsistent modCount. When you are iterating over ArrayList then Iterator's next() method keep track of modCount. If you modify the collection by adding or removing element then modCount will change and it will not match with the expected modCount, hence Iterator will throw ConcurrentModificationException.

Removing Duplicates in an ArrayList by creating a Method

I have to write a method called removeDups that accepts an ArrayList of Strings and returns a copy of the ArrayList with all the duplicates removed. I have to return a new ArrayList with no duplicate basically.
import java.util.ArrayList;
public class Duplicates {
public static ArrayList <String> removeDups(ArrayList<String> myArray) {
for (String item: myArray ) {
ArrayList <String> noDuplicate = new ArrayList <String>();
if (!noDuplicate.contains(item)) {
noDuplicate.add(item);
}else
;
return noDuplicate;
}
}
}
As a beginner coder, I am having trouble writing this code.
You need to modify few things to make it work (and to have cleaner code):
when you do not need ArrayList<String> you should work with interface List<String>
you should initiate noDuplicate array in the first line of method
you should check the condition !noDuplicate.contains(item) and if so just add item to noDuplicate list
rename the method from removeDups to removeDuplicates
Working code:
public static List<String> removeDuplicates(List<String> myArray) {
List<String> noDuplicate = new ArrayList<>();
for (String item : myArray) {
if (!noDuplicate.contains(item)) {
noDuplicate.add(item);
}
}
return noDuplicate;
}
If you will take a look on Java streams you can do the same thing using:
List<String> noDuplicate = myArray.stream()
.distinct()
.collect(Collectors.toList());

Type mismatch: convert from String to List<String>

I have in mind the algorithm of my school-class program, but also difficulty in some basics I guess...
here is my code with the problem:
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
String allWords = System.getProperty("user.home") + "/allwords.txt";
Anagrams an = new Anagrams(allWords);
for(List<String> wlist : an.getSortedByAnQty()) {
//[..............];
}
}
}
public class Anagrams {
List<String> myList = new ArrayList<String>();
public List<String> getSortedByAnQty() {
myList.add("aaa");
return myList;
}
}
I get "Type mismatch: cannot convert from element type String to List"
How should initialise getSortedByAnQty() right?
an.getSortedByAnQty() returns a List<String>. When you iterate over that List, you get the individual Strings, so the enhanced for loop should have a String variable :
for(String str : an.getSortedByAnQty()) {
//[..............];
}
If the main method should remain as is, you should change getSortedByAnQty to return a List<List<String>>.
char[] cArray = "MYString".toCharArray();
convert the string to an array as above and then iterate over the character array to form a list of String as below
List<String> list = new ArrayList<String>(cArray.length);
for(char c : cArray){
list.add(String.valueOf(c));
}

Categories