Adding An ArrayList<String> to ArrayList<ArrayList<String>> [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm currently attempting to save an ArrayList of Strings to an ArrayList of Arrays of Strings. Below code shows the basics of what I'm attempting.
ArrayList<ArrayList<String>> groupCollection= new ArrayList<ArrayList<String>>();
ArrayList<String> m_listItems = new ArrayList<String>();
groupCollection.add(m_listItems);
I add Strings to m_listItems using the same .add() functionality and it adds string correctly.
But in the debugger, when I attempt to add m_listItems (that does infact have an array of values in it) into the first index of groupCollection, it adds a null array into the first index.

Your code is fine, that's not a null, just an empty array list!

You need to add objects to your m_listitems list, m_listitems.add("foo"); execute you groupCollection.add(m_listItems); method and you should see a different result.

Answers above are certainly correct.
Just to add few details.
We created a ArrayList of ArrayList of String named groupCollection. And ArrayList named m_listItems.
Create another ArrayList for example n_ListItems. And add strings to both ArrayList.
ArrayList<String> m_listItems = new ArrayList<String>();
m_listItems.add("Hello");
m_listItems.add("Welcome");
ArrayList<String> n_listItems = new ArrayList<String>();
n_listItems.add("Hi!");
n_listItems.add("Wel..");
n_listItems.add("Come..");
Add both lists to groupCollection.
ArrayList<ArrayList<String>> groupCollection= new ArrayList<ArrayList<String>>();
groupCollection.add(m_listItems);
groupCollection.add(n_listItems);
We have added 2 arraylists to our ArrayList of ArrayList of String. To see the working of this program, I am displaying list using Iterator.
Iterator<ArrayList<String>> iterator = groupCollection.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
This will give output as follows.
[Hello, Welcome]
[Hi!, Wel.., Come..]
Now we can clearly see the way this program is working.

Related

If I have a HashMap where the values are a list, can I stream a certain index of that list into a new list? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am looking to take a Hashmap that has many key/value pairs where each value has a list. I want to take an index, and make a list based on that index.
Essentially I am looking to take this code and turn it into a stream.
HashMap < Integer , List< Object >> map = new HashMap();
//name //age
map.put("1", new List("Bob",20));
map.put("2", new List("Jim",37));
map.put("3", new List("Dan",30));
map.put("3", new List("Rick",40));
List < Integer > s = new ArrayList();
map.values().forEach(e - >
{
s.add(( Integer ) e.get(1)); //looking to extract all of the ages into
}); // a new list.
In my use case, each index of the list is a different type of object, so in this case I tried to use a String and an Integer. I mention this in case there is a way to select an item based on an object's type to put into the new list. I had found this example that mentioned "groupingBy" as a Collector's option, but It doesn't seem to work for my use-case
Shortcut for adding to List in a HashMap
Thank you for any help
Make a stream of the map's values collection, use Stream.map to extract the values you care about, and then Stream.collect to make a new collection.
List<Integer> ages = map.values().stream()
.map(list -> (Integer) list.get(1))
.collect(Collectors.toList());
I agree with the commenter on the question who said you should really make these into actual POJO objects - the code will be a lot clearer and less error prone if you do. If you go that route then you can use a method reference to get the ages:
.map(Person::getAge)

How to make ArrayList of hashset in java? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to make ArrayList of HashSet and use it.
**My Problem:**
I will get an Integer N as an user input.
I have to make a hashset and put some values in it.
Then add it to ArrayList and above step is to be done N times.
After it I have to check whether a element is present in the first/second/third/... or Nth hashset in ArrayList.
To check value in which hashset is also given by user.
I dont have to convert my ArrayList to hashset either I have to make ArrayList to hashset.
Just make an ArrayList of HashSets :
ArrayList<HashSet<Integer>> list = new ArrayList<HashSet<Integer>>();
Then create HashSets, fill them, and put them in your ArrayList normally.
HashSet<Integer> set = new HashSet<Integer>();
set.add(1);
set.add(whateverIntValue);
list.add(set);
You can then get the nth HashSet of your list using list.get(n).
List<Set<Integer>> sets = new ArrayList<>();
sets.add(someSet());
sets.add(someSet());
sets.add(someSet());
Set<Integer> someSet() {
Set<Integer> set = new Hashset<>();
Collections.addAll(set, 2, 3, 5, 7, 11);
return set;
}
This makes a distinction between specification / interface of variables an method parameters and results, and implementation / implementing class.
So you can change the implementation, say to a sorted TreeSet without pain.

Dynamic resizing of Array in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I wanted to use Dynamic Array in Java,
I will be declaring the array statically,where i will input values into the array ,once the array gets full i will reintialize the array size.
Whether the contents of the array will be removed or it will be maintained.
The contents are deleted in my program ,whether that is expected or not ?
Example
class a
{
static int arr[]=new int[10];
arr[]={1,2,3,4,5};
public static void main(String args[])
{
int N=35;
arr=new int[N];
arr[]={1....35};
}
}
Yes because when you think you're re-sizing it you're actually creating a new array with a different size. That is very much expected!!!
When you write:
arr=new int[N]
you actually discard your array object and create a new array of int of size N. This new object will not contain your previous array's values.
If you create a larger array, you must copy the previous values to it.
Better still, use one of Java's data structures such as Vector<Integer> or ArrayList<Integer>. These use dynamic arrays, but you don't have to know about it and shouldn't worry - they just work...
Better use arraylist, arraylist can grow which is not possible with arrays. if you to copy the contents into another array with different size use System.arraycopy() but previous array will exist. better way is using arraylist or vector
Arrays in Java are of fixed size. Use ArrayLists which is a collection & can dynamically scale.
Instead of
Integer[] ints = new Integer[x]
use
List<Integer> ints = new ArrayList<Integer>();

What are the advantages to call a class as an ArrayList in Java? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Suppose:
if I call one of my classes to my Main method, how many ways I can use the object ArrayList to make the list useful?
eg:
ArrayList <Account> listOfAccounts = new ArrayList<>();
Can I use listOfAccounts as Integer? if yes, how? or how to covert listOfAccounts as Integer ArrayList so that I can use them as in the method below?
class method:
int findMax(ArrayList <Integer> numberOfAccount){};
print in main method:
println("Maximum amount of money"+findMax(listOfAccounts));
Any help to clear the confusion will be appreciated. Thanks
If you just need to count the number of accounts you can do
int size = listOfAccounts.size();
if you want to extract a list of numbers from those accounts you can do
List<Integer> numberOfAccounts = listOfAccounts.stream()
.map(a -> a.getNum())
.collect(Collectors.toList());
how many ways I can use the object ArrayList to make the list useful?
Too many to count.
Can I use listOfAccounts as Integer?
Its a List of Accounts. If you want to use it as a list of Integers, you have to create a new List which contains the Integers you want.
how to covert listOfAccounts as Integer ArrayList so that I can use them as in the method below?
You can't convert the list, but you can get an integer out. I suggest you read the Javadoc for this class for more details.
int i = numberOfAccounts.get(i);
or
for(int i : numberOfAccounts) {
// iterate over the list
or use t as a Stream
numberOfAccounts.stream()
.forEach(System.out::println);
how to use findMaximum(listOfAccounts)? as listOfAccounts is object, not an specific type arrayList.
If you just want the maximum for some field of an Account, you don't need to extract a List<Integer> first.
List<Account> accounts = ...
OptionalInt max = accounts.stream()
.mapToInt(Account::getNum)
.max();

How to remove Object in Java List? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have one existing code, where the written line is
private Rule[] ruleList;
Where Rule is a CLASS.
I want to remove all Rules which are added here in ruleList.
but as I click right it shows like this
If it is a List, how can I delete these rules from ruleList?
Thanks
The ruleList is an array and not a List. Thus you will not find a clear method.
But you can use
Arrays.fill(ruleList, null);
You have an array and not a list. Solution :
ruleList = new Rule[ruleList.length];
To remove all items from a List use clear()
If you want to remove all items in an array from a List use the remove method.
Example
public class Rules {
public static void main(String[] args) {
Rule[] rules = new Rule[2];
rules[0] = new Rules.Rule();
rules[1] = new Rules.Rule();
//Scenario 1
List<Rule> ruleList = new ArrayList<Rule>();
ruleList.add(Arrays.asList(rules)); //adds array to list
ruleList.clear(); //removes all items from List
//Scenario2
ruleList.add(Arrays.asList(rules)); //adds array to list
ruleList.remove(Arrays.asList(rules)); //remove all rules in [] form list
//Scenario3
Arrays.fill(rules, null); //removes all elements in array
}
static class Rule{
}
}
It is important to determine whether you are using a List or an Array. The provided code depicts an array, however the verbiage keeps referring to a List.
If you actually have a List and want to remove all elements see Scenario 1 in the example.
If you actually have a List and want to remove all elements in the array from the List see Scenario 2 in the example.
If you actually have array and want to remove all elements from the array see Scenario 3 in the example.

Categories