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.
Related
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 1 year ago.
Improve this question
If I had, say separate 3 nested ArrayLists of Strings, i.e., ArrayList<ArrayList<String>>:
What is the most efficient way of finding their intersection (common elements)?
Are there other data structures to replace the nested ArrayLists structure that could improve the efficiency of finding their intersection? (e.g. The first structure I can think of is using a Set, but I would like to see if there are other suggestions for this.)
Thanks in advance!
The intersection of two lists is done using the retainAll() method.
It update the list, so if you don't want that, you should copy the list first.
If you have more than 2 lists, you copy the first and then call retainAll() for each of the remaining lists.
ArrayList<ArrayList<String>> lists = ...
List<String> intersection = new ArrayList<>(lists.get(0));
for (List<String> list : lists.subList(1, lists.size()))
intersection.retainAll(list);
However performance will be a bad O(n*m), where n and m are the sizes of the two largest lists.
That is because retainAll() does a contains() against the list given in the parameter, which is a sequential search, for each element in the intersection list.
Performance can be improved to O(n), where n is the largest list, by converting the lists to sets.
List<String> intersection = new ArrayList<>(lists.get(0));
for (List<String> list : lists.subList(1, lists.size()))
intersection.retainAll(new HashSet<>(list));
In Java 8+, the for loop can be simplified to one of these:
lists.subList(1, lists.size()).stream().map(HashSet::new).forEach(intersection::retainAll);
lists.subList(1, lists.size()).forEach(list -> intersection.retainAll(new HashSet<>(list)));
i would use the list.retainAll method as in
private ArrayList<String> getIntersection(ArrayList<ArrayList<String>> lists) {
if(null == lists || lists.isEmpty()) {
return null;
}
ArrayList<String> intersection = lists.get(0);
lists.forEach(intersection::retainAll);
return intersection;
}
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)
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 5 years ago.
Improve this question
I am new in java ,now i need a help.I recently work in Spring Boot framework,
anyone help me for create and manipulate a list as shown here.
What you show in the image could be implemented by a List of List or a Map.
If the left number in the image starts at 0 and are consecutive numbers, declaring List<List<Integer>> is a correct approach.
You can populate it in this way :
List<List<Integer>> listOfList = new ArrayList<>();
listOfList.add(Arrays.asList(0,1,2,3));
listOfList.add(Arrays.asList(0,1,2,3));
And retrieve the values according to the requested index :
List<Integer> secondList = listOfList.get(1);
If the left number in the image doesn't start at 0 or are not consecutive numbers, declaring Map<Integer, List<Integer>> is a better approach.
For each integer key, you have a List of integer.
If the map should be sorted according to the insertion order, use a LinkedHashMap :
Map<Integer, List<Integer>> map = new LinkedHashMap<>();
If the map should be ordered according to the natural ordering of its keys, use a TreeMap :
Map<Integer, List<Integer>> map = new TreeMap<>();
Of course you could implement it with a List of List such as
List<List<Integer>> but it would be less meaningful and more cumbersome.
I believe you can use list within a list concept. Here each element of the list is itself a list.
List<List<ClassYouWant>> listOfLists = new ArrayList<>();
Inserting data into this list:
List<List<ClassYouWant>> outerList= new ArrayList<>();
List<ClassYouWant> innerList = new ArrayList<>();
outerList.add(innerList );
Also you can achieve the same with other Collection data structures i.e Set within a Set or Map within a Map.
Additionally if you have a scenario where each list can represented by a unique value you can use List within Map
Map<AnyClass , List<ClassYouWant>> map = new HashMap<>();
AnyClass - Can be any unique value which represents your class
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>();
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();