Print ArrayList - java

I have an ArrayList that contains Address objects.
How do I print the values of this ArrayList, meaning I am printing out the contents of the Array, in this case numbers.
I can only get it to print out the actual memory address of the array with this code:
for(int i = 0; i < houseAddress.size(); i++) {
System.out.print(houseAddress.get(i));
}

list.toString() is good enough.
The interface List does not define a contract for toString(), but the AbstractCollection base class provides a useful implementation that ArrayList inherits.

Add toString() method to your address class then do
System.out.println(Arrays.toString(houseAddress));

From what I understand you are trying to print an ArrayList of arrays and one way to display that would be
System.out.println(Arrays.deepToString(list.toArray()));

since you haven't provide a custom implementation for toString() method it calls the default on which is going to print the address in memory for that object
solution
in your Address class override the toString() method like this
public class Address {
int addressNo ;
....
....
...
protected String toString(){
return Integer.toString(addressNo);
}
now when you call
houseAddress.get(i) in the `System.out.print()` method like this
System.out.print( houseAddress.get(i) ) the toString() of the Address object will be called

You can simply give it as:
System.out.println("Address:" +houseAddress);
Your output will look like [address1, address2, address3]
This is because the class ArrayList or its superclass would have a toString() function overridden.
Hope this helps.

assium that you have a numbers list like that
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
if you print the list
//method 1
// Conventional way of printing arraylist
for (int number : numbers) {
System.out.print(number);
}
//method 2
// Lambda Expression to print arraylist
numbers.forEach((Integer value) -> System.out.print(value));
//method 3
// Lambda Expression to print arraylist
numbers.forEach(value -> System.out.print(value));
//method 4
// Lambda Expression (method reference) to print arraylist
numbers.forEach(System.out::print);

Are you saying that ArrayList is storing addresses of arrays because that is what is returning from the toString call, or because that's actually what you're storing?
If you have an ArrayList of arrays (e.g.
int[] arr = {1, 2, 3};
houseAddress.add(arr);
Then to print the array values you need to call Arrays.deepToString:
for (int i = 0; i < houseAddress.size(); i++) {
System.out.println(Arrays.deepToString(houseAddress.get(i)));
}

public void printList(ArrayList<Address> list){
for(Address elem : list){
System.out.println(elem+" ");
}
}

I am not sure if I understood the notion of addresses (I am assuming houseAddress here), but if you are looking for way a to print the ArrayList, here you go:
System.out.println(houseAddress.toString().replaceAll("\\[\\]", ""));

Since Java 8, you can use forEach() method from Iterable interface.
It's a default method. As an argument, it takes an object of class, which implements functional interface Consumer. You can implement Consumer locally in three ways:
With annonymous class:
houseAddress.forEach(new Consumer<String>() {
#Override
public void accept(String s) {
System.out.println(s);
}
});
lambda expression:
houseAddress.forEach(s -> System.out.println(s));
or by using method reference:
houseAddress.forEach(System.out::print);
This way of printing works for all implementations of Iterable interface.
All of them, gives you the way of defining how the elements will be printed, whereas toString() enforces printing list in one format.

Simplest way to print an ArrayList is by using toString
List<String> a=new ArrayList<>();
a.add("111");
a.add("112");
a.add("113");
System.out.println(a.toString());
Output
[111, 112, 113]

Put houseAddress.get(i) inside the brackets and call .toString() function: i.e Please see below
for(int i = 0; i < houseAddress.size(); i++) {
System.out.print((houseAddress.get(i)).toString());
}

This helped to me:
System.out.println(Arrays.toString(codeLangArray.toArray()));

public static void main(String[] args) {
List<Moyen> list = new ArrayList<Moyen>();
Moyen m1 = new Moyen();
m1.setCodification("c1");
m1.setCapacityManager("Avinash");
Moyen m2 = new Moyen();
m2.setCodification("c1");
m2.setCapacityManager("Avinash");
Moyen m3 = new Moyen();
m3.setCodification("c1");
m3.setCapacityManager("Avinash");
list.add(m1);
list.add(m2);
list.add(m3);
System.out.println(Arrays.toString(list.toArray()));
}

You can use an Iterator. It is the most simple and least controvercial thing to do over here. Say houseAddress has values of data type String
Iterator<String> iterator = houseAddress.iterator();
while (iterator.hasNext()) {
out.println(iterator.next());
}
Note : You can even use an enhanced for loop for this as mentioned by me in another answer

if you make the #Override public String toString() as comments,
you will have the same results as you did.
But if you implement your toString() method, it will work.
public class PrintingComplexArrayList {
public static void main(String[] args) {
List houseAddress = new ArrayList();
insertAddress(houseAddress);
printMe1(houseAddress);
printMe2(houseAddress);
}
private static void insertAddress(List address)
{
address.add(new Address(1));
address.add(new Address(2));
address.add(new Address(3));
address.add(new Address(4));
}
private static void printMe1(List address)
{
for (int i=0; i<address.size(); i++)
System.out.println(address.get(i));
}
private static void printMe2(List address)
{
System.out.println(address);
}
}
class Address{
private int addr;
public Address(int i)
{
addr = i;
}
#Override public String toString()
{
Integer iAddr = new Integer (addr);
return iAddr.toString();
}
}

You can even use an enhanced for loop or an iterator like:
for (String name : houseAddress) {
System.out.println(name);
}
You can change it to whatever data type houseAddress is and it avoids unnecessary conversions

Make sure you have a getter in House address class and then use:
for(int i = 0; i < houseAddress.size(); i++) {
System.out.print(houseAddress.get(i)**.getAddress()**);
}

you can use print format if you just want to print the element on the console.
for(int i = 0; i < houseAddress.size(); i++) {
System.out.printf("%s", houseAddress.get(i));
}

Assuming that houseAddress.get(i) is an ArrayList you can add toString() after the ArrayList :
for(int i = 0; i < houseAddress.size(); i++) {
System.out.print(houseAddress.get(i).toString());
}
A general example:
ArrayList<Double> a = new ArrayList();
a.add(2.);
a.add(32.);
System.out.println(a.toString());
// output
// [2.0, 32.0]

This is a simple code of add the value in ArrayList and print the ArrayList Value
public class Samim {
public static void main(String args[]) {
// Declare list
List<String> list = new ArrayList<>();
// Add value in list
list.add("First Value ArrayPosition=0");
list.add("Second Value ArrayPosition=1");
list.add("Third Value ArrayPosition=2");
list.add("Fourth Value ArrayPosition=3");
list.add("Fifth Value ArrayPosition=4");
list.add("Sixth Value ArrayPosition=5");
list.add("Seventh Value ArrayPosition=6");
String[] objects1 = list.toArray(new String[0]);
// Print Position Value
System.err.println(objects1[2]);
// Print All Value
for (String val : objects1) {
System.out.println(val);
}
}
}

JSON
An alternative Solution could be converting your list in the JSON format and print the Json-String. The advantage is a well formatted and readable Object-String without a need of implementing the toString(). Additionaly it works for any other Object or Collection on the fly.
Example using Google's Gson:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
...
public static void printJsonString(Object o) {
GsonBuilder gsonBuilder = new GsonBuilder();
/*
* Some options for GsonBuilder like setting dateformat or pretty printing
*/
Gson gson = gsonBuilder.create();
String json= gson.toJson(o);
System.out.println(json);
}

Add toString() method to your class
houseAddress.forEach(System.out::println);

Consider using an "Enhanced for loop" I had to do this solution for a scenario in which the arrayList was coming from a class object
changing the String datatype to the appropriate datatype or class object as desired.
ArrayList<String> teamRoster = new ArrayList<String>();
// Adding player names
teamRoster.add("Mike");
teamRoster.add("Scottie");
teamRoster.add("Toni");
System.out.println("Current roster: ");
for (String playerName : teamRoster) {
System.out.println(playerName);
// if using an object datatype, you may need to use a solution such as playerName.getPlayer()
}

Related

How to add characters in the middle of a word in an arraylist in java?

I'm practicing ArrayList's. I'm trying to make it so that every time is is in the ArrayList, it is then followed with not. For instance [is sky, is, this is blue, is is, is not] after running through the method comes out as [is not sky, is not, this is not blue, is not is not, is not not]. However, with my code right now it does not change. I am new to Java, so I would really appreciate any pointers!
class Main {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("is sky");
list.add("is");
list.add("this is blue");
list.add("is is");
list.add("is not");
System.out.println(replace(list));
}
public static ArrayList<String> replace(ArrayList<String> list) {
for (int i = 0; i < list.size(); i++) {
if (list.subList(i, i + 1).equals("is")) {
list.add(i + 1, " not");
}
}
return list;
}
}
First solve the simplest case. Forget the list for a moment and do the substitution with just one String.
String replaceOne(String original) {
return original.replace("is", "is not");
}
Test this method.
String replaced = replaceOne("sky is");
The test passes if this replaced variable is equal to sky is not.
Once you've guaranteed that, move on to the general case, with a list.
void replaceMany(ArrayList<String> original) {
for (int i = 0; i < original.size(); i++) {
original.set(i, replaceOne(original.get(i)));
}
}
Note that if you're running this inside a static method, the above methods need to be static (i.e. static void, static String).
With Java 8 you could also solve this problem differently. Instead of using the set method on the array list, you could use lambdas and a collector to get a modified list (preserve the original and get another list with the modified strings). Something like:
List<String> replaced = original.stream()
.map(s -> replaceOne(s))
.collect(Collectors.toList());
With Java 9, you can simplify your code as follows:
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<String> list = List.of(
"is sky", "is", "this is blue", "is is", "is not");
System.out.println(replace(list));
}
public static List<String> replace(List<String> list) {
return list.stream()
.map(str -> str.replace("is", "is not"))
.collect(Collectors.toList());
}
}
Output:
[is not sky, is not, this not is not blue, is not is not, is not not]
Because your if statement is always false. Method subList returns list that you compare with string in line:
list.subList(i, i+1).equals("is")

How to edit the contents of an ArrayList in-place while looping [duplicate]

This question already has answers here:
How to change value of ArrayList element in java
(7 answers)
Closed 6 years ago.
Assume I have an ArrayList of Strings that holds the words, "hello" and "world". I want to add the word "java" to the end of each.
I have tried to do it while looping, but did not succeed. Please suggest me a method for the same.
The other way, I found was to create a different ArrayList and copy contents, however I don't think is efficient in terms of space.
import java.util.ArrayList;
public class EditArrayListInLoop {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("hello");
arrayList.add("world");
/* This does not work */
/*for(int i = 0;i<arrayList.size();i++)
{
arrayList.get(i) += "java";
}*/
ArrayList<String> arrayList2 = new ArrayList<String>();
for(int i = 0;i<arrayList.size();i++)
{
String test = arrayList.get(i);
test += "java";
arrayList2.add(test);
}
System.out.println(arrayList2);
}
}
test += "java"; doesn't change the content of the String returned by arrayList.get(i). It creates a new String. Strings are immutable, so there isn't any way to change the String objects within the List. You can only replace them by new String objects.
Use arrayList.set(index,newValue) to replace the i'th element of the List:
for(int i = 0;i<arrayList.size();i++)
{
arrayList.set(i,arrayList.get(i)+"java");
}
I think you should manipulate the first list only. Using an another list is not an optimal solution.
Here's the code.
Output
[hellojava, worldjava]
Code
import java.util.ArrayList;
public class EditArrayListInLoop {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("hello");
arrayList.add("world");
for(int i = 0;i<arrayList.size();i++)
arrayList.set(i, arrayList.get(i).concat("java"));
System.out.println(arrayList);
}
}
Please note that Strings are immutable. Whenever you change the content of String, you're not actually appending anything behind the scenes. You are creating a completely new String.
If the contents of your Strings are expected to change, then the advisable way is to use the StringBuilder class instead:
Documentation
The principal operations on a StringBuilder are the append and insert
methods, which are overloaded so as to accept data of any type. Each
effectively converts a given datum to a string and then appends or
inserts the characters of that string to the string builder. The
append method always adds these characters at the end of the builder;
the insert method adds the characters at a specified point.
Here's the code:
import java.util.ArrayList;
public class EditArrayListInLoop {
public static void main(String[] args) {
ArrayList<StringBuilder> arrayList = new ArrayList<StringBuilder>();
arrayList.add(new StringBuilder("hello"));
arrayList.add(new StringBuilder("world"));
for(int i = 0;i<arrayList.size();i++)
arrayList.set(i, arrayList.get(i).append("java"));
System.out.println(arrayList);
}
}
P.S.: If such synchronization is required then it is recommended that StringBuffer be used.
try using the set method.
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("hello");
arrayList.add("world");
for(int i = 0;i<arrayList.size();i++)
{
String str = arrayList.get(i);
arrayList.set(i, str + " java");
}
for(int i = 0;i<arrayList.size();i++)
{
String str = arrayList.get(i);
System.out.println(str);
}
You are looking for:
arrayList.set(i, arrayList.get(i) + "java");
More info on ArrayList: https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

Java, get all variable values of a class

So I have a class called Test:
public class Test{
protected String name = "boy";
protected String mainAttack = "one";
protected String secAttack = "two";
protected String mainType"three";
protected String typeSpeak = "no spoken word in super class";
//Somehow put all the class variables in an Array of some sort
String[] allStrings = ??(all class' strings);
//(and if you feel challenged, put in ArrayList without type declared.
//So I could put in, not only Strings, but also ints etc.)
public void Tester(){
//Somehow loop through array(list) and print values (for-loop?)
}
}
As you can see, I want to put all the class variables in an Array or ArrayList (or something similar) automatically.
And next I want to be able to loop through the array and print/get the values.
Preferably using an enhanced-for loop.
As other said, don't do this. But this is how:
Class<?> cl = this.getClass();
List<Object> allObjects = new ArrayList<Object>();
for (java.lang.reflect.Field f: cl.getDeclaredFields())
{
f.setAccessible(true);
try
{
Object o = f.get(this);
allObjects.add(o);
}
catch (Exception e)
{
...
}
}
for (Object o: allObjects)
System.out.println(o);
If you really really need do this you need to use Reflection.
However a much better approach would be to store the values in a Map (probably a HashMap) and then you can query/set/etc them from that easily.
You can use Map or Hashmap to store variables and its values instead of Array or Arraylist
HashMap is an object that stores both “key/value” as a pairs. In this article, we show you how to create a HashMap instance and iterates the HashMap data.
Why not use a HashMap for the values and iterate through that?
Iterate through a HashMap
Do this.
String threeEleves = "sky";
String sevenDwarves = "stone";
String nineMortal = "die";
String oneRing[] = new String[] // <<< This
{
threeElves,
sevenDwarves,
nineMortal
}
or do this
// in some class.
public void process(final String... varArgs)
{
for (String current : varArgs)
{
}
}
String one = "noodles";
String two = "get";
String three = "in";
String four = "my";
String five = "belly";
process (one, two, three, four, five);

Transform Set<Keyword> into String[]

I have an object Keyword that stores a String with the text of the keyword and a set o keywords (Set<Keyword>) that I need to transform into a String array. Is there a quick/easy way to do this or I need to iterate the set and add each keyword one by one?
EDIT:
For those asking for Keyword class:
#Entity
public class Keyword {
// ...
#Basic
private String value;
// ...
// Getters & Setters
}
Every class that implements Collection intefrace (and that includes Set) has toArray() method:
String[] array= set.toArray(new String[0]);
In case of a set that is parametrized with some other type, e.g. Set<Keyword> you would have to do something like:
Keyword[] array= set.toArray(new Keyword[0]);
String[] stringArray= new String[array.length];
for (int i=0; i<array.length; i++) {
stringArray[i]= array[i].getThatString();
}
Try this:
String[] arr = set.toArray(new String[set.size()]);
... is what I would have said, if you had a Set<Object>.
No, there is no way to directly convert a Set<Keyword> to a String[] since there is no direct relationship between Keyword and String. You will have to iterate over the set:
String[] arr = new String[set.size()];
int i = 0;
for (Keyword word : set)
arr[i++] = word.toString();
If you use Guava, you may use this:
Lists.transform(Lists.newArrayList(theSet), Functions.usingToString())
.toArray(new String[theSet.size()])
And this only scratches the surface of what Guava can actually do.
There is no specific way to do this . You can either convert Set to Object[] using set.toArray and then iterate over the array
or
iterate over the set directly
You may need to add toString() method to your Keyword class as shown below. Or you can use a separate transformer class/method.
class Keyword {
private String value;
Keyword(String v) {
this.value = v;
}
public String toString() {
return value;
}
}
.
I would say iterate the set and add each keyword one by one is your best possible strategy.
System.out.println(toStringArray(set));
.
private static String[] toStringArray(Collection<?> set) {
String[] arr = null;
if (set != null) {
arr = new String[set.size()];
int i = 0;
for (Object o : set) {
arr[i++] = o.toString();
}
}
return arr;
}
.
However if you really want, you can have a dirty workaround as shown below. Only issue here is that your keyword value cannot contain comma (,) as it is used by split() method.
String str = set.toString();
str = str.substring(1, str.length() - 1);
String[] asStringArray = str.split(",");
System.out.println(asStringArray);

Looping in ArrayLists with a Method

With much assistance I have developed a method that makes anagrams and then adds them into an ArrayList.
public void f(String s, String anagram, ArrayList<String> array)
{
if(s.length() == 0)
{
array.add(anagram);
return;
}
for(int i = 0 ; i < s.length() ; i++)
{
char l = s.charAt(i);
anagram = anagram + l;
s = s.substring(0, i) + s.substring(i+l, s.length());
f(s,anagram,array);
}
}
The problem is when I attempt to use this function to make ArrayLists in a loop that adds Strings from one ArrayList to another, I get an error saying I can't use a void, and the method f() is void.
List<String> Lists = new ArrayList<String>(); //makes new array list
for(String List : words)
{ //takes values from old array list
List.trim();
Lists.add(f(List,"",new ArrayList<String>())); //this is where it doesn't work
}
Let me clarify once more:
I want to use this function to insert ArrayLists of anagrams into each position in another ArrayList. The anagram Lists are derived from Strings that are being read from one list to another. I tried changing the method to static but that doesn't work, I also removed the return; in the method once, but that doesn't fix it either.
How do I make this whole thing work?
The error happens because the method f() is void, meaning: it doesn't return any value that can be added to the ArrayList.
The answer of invoking f() is stored in the ArrayList passed as a parameter to f, you should probably use that ArrayList to add all of its elements to Lists. Something like this:
List<String> lists = new ArrayList<String>();
for (String list : words) {
list.trim();
ArrayList<String> answer = new ArrayList<String>();
f(list, "", answer);
lists.addAll(answer);
}
Your method header for F needs to look like this:
public String f(String s, String anagram, ArrayList<String> array)
And then you return a String value to add to that ArrayList you are using.
Your function definition for f() shows the return value of type void. So looking at your code you're attempting to do this:
Lists.add(void);
which is obviously illegal.
Your choice really is to have the ArrayList declared in a greater scope.
private List<String> anagrams;
public void f(String s, String anagram) {
...
anagrams.add(anagram);
...
}
....
for(String List : words) {
//takes values from old array list
anagrams = new ArrayList<String>();
List.trim();
f(list,"");
Lists.add(anagrams); //this is where it doesn't work
}

Categories