java create string array from multiple arraylist [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
i have multiple arraylist like this:
arraylist
arrayList.add(product1);
arrayList.add(product2);
arrayList.add(product3);
arrayList.add(product4);
.
.
.
.
arrayList.add(productn);
arraylist2
arrayList2.add(name1);
arrayList2.add(name2);
arrayList2.add(name3);
arrayList2.add(name4);
.
.
.
arrayList2.add(namen);
arraylist3
arrayList3.add(id1);
arrayList3.add(id2);
arrayList3.add(id3);
arrayList3.add(id4);
.
.
.
arrayList3.add(idn);
i want to create string of array combine of arraylists above
with index of string in arraylist
so something like this
string[1] = {product1,name1,id1 }
string[2] = {product2,name2,id2 }
.
.
.
string[n] = {productn,namen,idn }
any idea how to do it?
sorry before
and thanks in advance

Make a class and then an array of instances/objects of that class. Here's an example,
public class Product{
String name;
String id;
public Product(String name, String id){ //constructor for the object
this.name = name;
this.id = id;
}
}
Then in your main method, create an array of type Product and added instances of Product to the array,
Product[] products = new Product[10];
products[0] = new Product("cheese", "0");
System.out.println(products[0].name + " " + products[0].id);
You can adjust to your liking, for example you can edit the Product class by adding more instance fields other than name and id, resize the array, change the array to an arraylist, etc..

Do you mean something like that?
int size = 10;
List<String> arr1 = new ArrayList<>();
List<String> arr2 = new ArrayList<>();
List<String> arr3 = new ArrayList<>();
String[] string = new String[size];
for (int i = 0; i < size; i++) {
string[i] = arr1.get(i) + arr2.get(i) + arr3.get(i);
}

You can loop through them in one loop and create an object with it.
we need to create a class
// The data type will change based on the data type you have them as
public class MyObject {
private Product product;
private Name name;
private Id id;
public MyObject(Product p, Name n, Id i) {
product = p;
name = n;
id = i;
}
// All Getters & toString()
}
Now for the loop :
List< MyObject> myList = new ArrayList < MyObject >();
for ( int i=0 ; i < arrayList || i < arrayList2 || i < arrayList3 ) {
myList.add(new MyObject(arrayList.get(i),arrayList2.get(i),arrayList3.get(i)))
}
Note you can override the toString method in you class to get the output in the way you want.
EG:
public String toString() {
return "Name: '" + this.name + "', ID: '" + this.id + "', Product: '" + this.product + "'";
}

public static void main(String[] args) {
List<String> arrayList = new ArrayList<>();
arrayList.add("product1");
arrayList.add("product2");
arrayList.add("product3");
List<String> arrayList2 = new ArrayList<>();
arrayList2.add("name1");
arrayList2.add("name2");
arrayList2.add("name3");
List<String> arrayList3 = new ArrayList<>();
arrayList3.add("id1");
arrayList3.add("id2");
arrayList3.add("id3");
int n = arrayList.size();
List<String[]> productlist = new ArrayList<>();
for(int i = 0; i< n;i++){
productlist.add(new String[]{arrayList.get(i),arrayList2.get(i),arrayList3.get(i)});
System.out.println(Arrays.toString(productlist.get(i)));
}
}

Related

How to creart an ArrayList from array?

I am trying to create an ArrayList from a given array. This is the array I have:
public class Warehouse
{
private final static int MAX = 60;
private Item [] stock;
private int numItems;
public Warehouse()
{
stock = new Item[MAX];
numItems = loadData();
}
Now where should I change the processing from an array to an arraylist? Is this supposed to be done in the constructor or somewhere else? Thanks.
Why not use this?
List<Item> stockList = Arrays.asList(stock);
Just keep a separate class for the array and within the class that you want to get that specific array you can create an ArrayList Object.
public class ArrayaData {
public int Id;}
And the within the next class,
public class ClassYouWant {
ArrayList<ArrayaData> arrayList ;
}
and when ever you want to add a value to that array just create a new instance and then save it.
arrayList = new ArrayList<ArrayaData>();
arrayList.Id = "Value you want.."
arrayList = new ArrayList<ArrayaData>();
arrayList.Id = "Value 2 you want.."
Or you can simply set it in a Loop as well,
int arraySize = 5; //Size of the array you want
for (int i = 0; i < arraySize; i++) {
arrayList = new ArrayList<ArrayData>();
arrayList.Id = "Value you want";
}
And to get the vlaues you can use a Loop also,
int arraySize = arrayList.size(); //Size of the created arrayList
int value;
for (int i = 0; i < arraySize; i++) {
value = arrayList.get(i);
Toast.makeText(this, "Value " + i + ":" + value, Toast.LENGTH_SHORT).show();
}
Hope this helps..

android listview adapter combine two arrays

I'm wornig sqllite.i have some tables and i select name for example Customer Table and Price from AnotherTable. and i received two array list .first name's array list and secods price's array list.
this is a my source
private ArrayList<GetDictioanyClassByPosition> GetPKFromTable() {
price_array.clear();
ArrayList<GetDictioanyClassByPosition> my_list = d_Helper
.getAllPriceByPosition(0);
for (int i = 0; i < my_list.size(); i++) {
String AllPrice = my_list.get(i).getDictionaryPrice();
GetDictioanyClassByPosition cnt = new GetDictioanyClassByPosition();
System.err.println(AllPrice + "AllPrice");
cnt.setDictionaryPrice(AllPrice);
price_array.add(cnt);
}
return price_array;
}
this is a method to check price's array list and this method check name's array list
public void AllInfoFromLoanAnalysis() {
name_list.clear();
ArrayList<GetAllDictionariesClass> contact_array_from_db = d_Helper
.getAllInformationFromLoanAnalysis_Table(1, 1);
Log.e("Sizee", contact_array_from_db.size() + "sizee");
for (int i = 0; i < contact_array_from_db.size(); i++) {
int DictionaryID = contact_array_from_db.get(i).getDictionaryID();
System.out.println(DictionaryID + "DictionaryID");
GetDictioanyClassByPosition object = new GetDictioanyClassByPosition();
String name = null ;
ArrayList<GetDictioanyClassByPosition> DictionaryIdList = d_Helper
.GetDictionaryIdList(DictionaryID);
System.out.println(DictionaryIdList.size() + "DictionaryIdList");
Log.e("Sizee2", DictionaryIdList.size() + "sizee2");
for (int j = 0; j < DictionaryIdList.size(); j++) {
name= DictionaryIdList.get(j).getDictionaryName();
Log.e("object", name + "object");
object.setDictionaryName(name);
name_list.add(object);
}
for (int j = 0; j < price_array.size(); j++) {
String AllPrice = price_array.get(i).getDictionaryPrice();
object.setDictionaryPrice(AllPrice);
object.setDictionaryName(name);
price_array.add(object);
}
agroproductslistview.setAdapter(agroproduct_adapter);
}
}
and i called my BaseAdapter Like this
_adapter = new LoanProductAdapter(
getApplicationContext(), R.layout.productlistadapter,
name_list);
public class GetDictioanyClassByPosition {
private String DictionaryName;
private String DictionaryPrice;
public String getDictionaryName() {
return DictionaryName;
}
public void setDictionaryName(String DictionaryName) {
this.DictionaryName = DictionaryName;
}
public String getDictionaryPrice() {
return DictionaryPrice;
}
public void setDictionaryPrice(String DictionaryPrice) {
this.DictionaryPrice = DictionaryPrice;
}
}
i can selected and show my prices and names in different array list but i want to marge both array list and would adapter in my list view
.how i can solve my problem?
if anyone knows solution please help me
thanks
Please refer below example.
public ArrayList<customObject> _historyArrayList = new ArrayList<customObject>();
public ArrayList<customObject> _completedArraylist = new ArrayList<customObject>();
For merging simply use:
_historyArrayList.addAll(_completedArraylist);
Note: Make sure your customObject are same

Java add items into class as an Array

I have simply this below class structure and I want to add any item to it.
public class Person implements Serializable {
private String name;
private String mobile;
public Person(String n, String e) { name = n; mobile = e; }
public String getName() { return name; }
public String getMobile() { return mobile; }
#Override
public String toString() { return name; }
}
I want to add any item like with this:
people = new Person[]{
new Person("Hi" , " programmer"),
new Person("Hello", " world")
};
My code is this and I want to add items into that by while() my code is don't correct.
people = new Person[]{};
while (phones.moveToNext())
{
people = new Person("Hi" , " programmer");
people = new Person("Hello", " world")
}
you have error in your source code you are trying to put Object of person into array so it will gives you compilation error
to overcome this problem first take List of Type Person and convert it into array and do your business logic on Array its better to use List instead of Array
List<Person> personlst = new ArrayList<Person>();
while (phones.moveToNext())
{
personlst.add(new Person("Hi" , " programmer"));
personlst.add(new Person("Hello", " world"));
}
Object[]arryPer = personlst.toArray();
Person[]people = new Person[arryPer.length];
for (int j = 0; j < arryPer.length; j++) {
people[j] = (Person) arryPer[j];
}
above code of block give you array of type people
You are not defining the number of elements that you want to push into array. Also you are not even making those elements to an array. You should do something like:
int i =0;
people = new Person[1000];// you need to define how many elements you need here or go for list
while (phones.moveToNext())
{
people[i++] = new Person("Hi" , " programmer");
people[i++] = new Person("Hello", " world")
}
Define first the size of your Person.
Person[] people = new Person[10];
then do your iteration for example.
for(int i = 0; i < 0; i++){
people[i] = new Person("Hi" , " programmer");
}
first put all elements in list then form the array:
List<Person> list = new ArrayList<Person>();
while (phones.moveToNext()) {
list.add(new Person("Hi", " programmer"));
list.add(new Person("Hello", " world"));
}
Person[] persons = new Person[list.size()];
list.toArray(persons);
}
Try Arrays.asList
http://www.tutorialspoint.com/java/util/arrays_aslist.html
Note - it is good only for a small number of elements as arrays generally take contiguous memory.
As people have stated above, list is any day better from space point of view.

How to convert ArrayList instanceObject to toString

i want to convert the instance of class which is in ArrayList to toString i have here my code
User class:
public class User {
// ...
public void setName(String name) {
this.fullname = name;
}
#Override
public String toString() {
return this.fullname;
}
public ArrayList<User> getTheLikers() {
ArrayList<User> user = new ArrayList<>();
user.add(this);
return user;
}
Post class:
public class Post {
public ArrayList<User> getLikers() {
User a = new User();
ArrayList<User> b = a.getTheLikers();
return b;
}
and here is the code where i should get the getLikers()
while(rs.next()) {
User a = new User();
Post b = new Post();
String name = rs.getString("people_who_like");
a.setName(name);
ArrayList c;
c = b.getLikers();
String liker = c.toString();
p.addElement(liker);
}
i have already convert it to toString as you can see.. but it shows that i have display my value but it is in null
To convert ArrayList into a String. That is specifically what the question says.
ArrayList c;
c = b.getLikers();
String liker = "";
for (String s : c){
liker += s + "\t";
}
When using Java 8 you can use String#join for this:
String liker = String.join(", ", c);
or the Stream API:
String liker = c.stream().collect(Collectors.joining(", "));
Pre Java 8 you have use e.g. Guava for this or write our own function
public static String listToString(final List<String> list) {
final StringBuilder result = new StringBuilder();
for (int i = 0; i < list.size() - 1; i++) {
result.append(list.get(i));
result.append(", ");
}
result.append(list.get(list.size() - 1));
return result.toString();
}
Even the list having the method List.toString() where u can get list into the String format.
how ever here the one thing that u can use your list to convert into the string.
Use the static variable for the list.
public class MainClass {
static ArrayList<String> arrayList = new ArrayList<String>();
public static void main(String args[]) {
arrayList.add("Krish");
arrayList.add("Krish1");
arrayList.add("Krish2");
arrayList.add("Krish3");
arrayList.add("Krish4");
System.out.println(arrayList.toString());
}
}
Similar u can use tostring method like this. if u using just arraylist then it will give out put in string format.
other way to do this.
public static String arrayliststring(ArrayList arrayList) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < arrayList.size(); i++) {
buffer.append(arrayList.get(i).toString() + " ");
}
return buffer.toString();
}
hope this helps and for java 8 as ifloop said that is correct.

How add, remove and save values in the haspmap [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am trying to write 3 methods say
1. getAddedTasks()
2. getRemovedTasks()
3. saveTasks()
get it done for the following
there two hashmap
1. is onscreen and 2. actual
onscreen: {} , actual: {}
step 1 : i have to use add button to add 3 tasks, 1,2,3 in onscreen , and actual will be empty
like this
onscreen: {1,2,3}, actual: {}
step 2 : when click save click save ->this shoul happen
getRemovedTasks()="", getAddedTasks()="1,2,3"
then hashmap status will be like this
onscreen: {1,2,3}, actual: {1,2,3}
step 3 : again i want add 4th value in onscreen
like this
onscreen: {1,2,3,4}, actual: {1,2,3}
simultaneously i want remove 3rd value
like this
onscreen: {1,2,4}, actual: {1,2,3}
step 4 : click save -> getRemovedTasks()="3", getAddedTasks()="4"
finally output should be like this
onscreen: {1,2,4}, actual: {1,2,4}
i tried with this following code
import java.util.*;
public class getList
{
private static HashMap<Integer, Object[]> dataz = new HashMap<Integer,Object[]>();
private static HashMap<Integer, Object[]> screen_dataz = new HashMap<Integer,Object[]>();
public final static Object[][] longValues = {{"10", "kstc-proc", "10.10.","5","O"},{"11", "proc-lvk1", "12.1.2.","4","O"},{"13", "trng-lvk1", "4.6.1.","3","O"}};
public static String sl, pid, tid, mval,status;
public static String findRowsRemoved()
{
ArrayList<String> datazList = new ArrayList<String>();
for(int index: dataz.keySet())
{
Object[] data = dataz.get(index);
datazList.add(data[1]+":"+data[2]);
}
for (int index: screen_dataz.keySet())
{
Object[] data = screen_dataz.get(index);
String check = data[1]+":"+data[2];
if (datazList.contains(check))
datazList.remove(check);
}
HashMap<String,String> p = new HashMap<String,String>();
for(String d: datazList)
{
String pId = d.split(":")[0];
String tId = d.split(":")[1];
if (p.containsKey(pId))
p.put(pId, p.get(pId)+","+tId);
else
p.put(pId, tId);
}
String fullStr = "";
for(String pId: p.keySet())
{
fullStr += pId + ":" + p.get(pId) + "|";
}
fullStr = fullStr.substring(0, fullStr.length()-1);
return fullStr;
}
public static void addTask(HashMap<Integer,Object[]> d, Object[] data)
{
d.put(screen_dataz.size(), data);
}
public static void saveTask()
{
System.out.println("Save Task");
System.out.println("-------------");
dataz.putAll(screen_dataz);
for (int i=0; i<longValues.length; i++)
{
for (int j=0; j<longValues.length; j++)
{
sl = (String) longValues[i][0];
pid = (String) longValues[i][1];
tid = (String) longValues[i][2];
mval = (String) longValues[i][3];
status = (String) longValues[i][4];
}
}
}
public static void main(String args[])
{
//addTask();
Object[] obj = new Object[5];
String[] strArray = new String[]{"1","kstc-proc","1.1","5","O"};
String[] strArray1 = new String[]{"2","proc-lvk1","1.2.","6","O"};
String[] strArray2 = new String[]{"3","proc-lvk1","1.3.","7","O"};
addTask(screen_dataz, strArray);
addTask(screen_dataz, strArray1);
addTask(screen_dataz, strArray2);
Object[] obj1= new Object[5];
String[] strArray3 = new String[]{"4","kstc-proc","1.4","8","O"};
addTask(dataz, strArray2);
addTask(dataz, strArray3);
String str = findRowsRemoved();
System.out.println("RowsRemoved: " + str);
str = findRowsAdded();
System.out.println("RowsAdded: " + str);
//saveTask();
}
}
public class multivalueHashmap {
private Map< Integer, List<Float> > map = new HashMap< Integer, List<Float> >();
public void add(Integer id, Float value){
if(!map.containsKey(id)){
map.put(id, new ArrayList<Float>());
}
map.get(id).add(value);
}
public void delete(Integer id, Float value){
if(!map.containsKey(id)){
return;
}
map.get(id).remove(value);
}
}
This way you can use the methods to easily add and remove items.

Categories