Java array values as hashset - java

I am new to Java and I literally have no idea how to do this.
I have this Java array:
String luni[];
luni = new String[] {"A","B","C"};
and I want each value A,B,C from the array to become a HashSet variable, like this:
Set<String> luni[0] = new HashSet<>(500);
Set<String> luni[1] = new HashSet<>(500);
Set<String> luni[2] = new HashSet<>(500);
Eventually having A,B,C as HashSet to which I can later use luni[0].add("string");
I hope you get the idea. How can I do this, it seems it won't work as I wrote it?

You can use a HashMap in your case it will have a String keys and HashSet values.
HashMap<String, HashSet<Whatever>> map
= new HashMap<String, HashSet<Whatever>>();

Original answer was:
If you just need to access each HashSet in the array by index,
luni[0].add("string"), then you simply have to define luni as an
array of Sets:
But in fact, you'll need to use an ArrayList of Sets (or use an array of raw Set, but that's not as good), and you'll still be able to use it with an index:
Note that this is only good if you don't have any actual use for the "A", "B", "C" and you just wanted to access the hashsets by index.
List<Set<String>> luni = new ArrayList<Set<String>>();
luni.add( new HashSet<String>(500) );
luni.add( new HashSet<String>(500) );
luni.add( new HashSet<String>(500) );
luni.get(0).add("String");

Either use:
Map<String, Set<String>> luni = new HashMap<>();
luni.put("A", new HashSet<String>(500));
luni.put("B", new HashSet<String>(500));
luni.put("C", new HashSet<String>(500));
// To add a value to B:
luni.get("B").add("some string");
or:
List<Set<String>> luni = new ArrayList<>(3);
luni.add(new HashSet<String>(500));
luni.add(new HashSet<String>(500));
luni.add(new HashSet<String>(500));
// To add a value to 'B' (index 1):
luni.get(1).add("some string");
I suggest using the first one. The second one uses index instead of A, B and C like you want.

Related

How to retrieve an element inside an ArrayList value in a HashMap?

I'm new to Java and I'm struggling to figure out something trivial.
I have a HashMap with keys of type String and values of type ArrayList <String>, and it returns something like this:
dict = {Color=[Blue, Purple]}
I'm struggling to figure out how I can grab a specific element from the array in the value of dict. Like if I got dict.value[0], it would return the string 'Blue'.
I've tried doing:
Object values = dict.values().toArray[0];
and I assumed that since I changed it to an array, I could do something like values.get(0) to get the first element, but that doesn't work because values is type Object. Any ideas on how to resolve this?
if your HashMap is like:
Map<String, List<String>> myColorsMap = new HashMap<>();
And after populating the map is like:
{Red=[firstRed, secondRed, thirdRed], Blue=[firstBlue, secondBlue, thirdBlue]}
then you can retrieve Blue's key value (a List) like:
String blueFirstElement = myColorsMap.get("Blue").get(0); // --> will give first element of List<String> stored against Blue key.
To get collection of all keys in your map (or "dictionary"):
myColorsMap.keySet();
will give:
[Red, Blue]
When you do:
Object values = dict.values().toArray[0];
First, this is wrong. What you were trying to do is this:
Object values = dict.values().toArray();
Which returns Object[] and it is ambiguous. No need to do that. Java's Map interface and HashMap implementation have a lot of utility methods for you to iterate and retrieve your values.
First, use .get() on map to get the ArrayList using key
List<String> colors = dict.get("Color");
Then use .get() on list to get the element using index
String color = colors.get(0);
You can do this in one line this way
String color = dict.get("Color").get(0);
You are trying with dict.values().toArray[0] which is wrong syntax thats the problem. dict.values() will return Collection<List<String>>, you can get List of values this way
List<List<String>> listOfValues = new ArrayList<>(colorsMap.values());
Then you can access each value by index using .get()
List<String> colors = listOfValues.get(0);
Note : HashMap don't store any order.
Cast to type of java.util.List, and then you can get value through index.
#SuppressWarnings("unchecked")
public static void main(String[] args) {
Map<String, List<String>> map = new HashMap<>(2);
map.put("color", Arrays.asList("blue", "yellow", "green", "white"));
map.put("size", Arrays.asList("small", "medium", "large"));
List<String> o = (List<String>) map.values().toArray()[0];
System.out.println(o.get(0)); //output is 'blue'
List<String> s = (List<String>) map.values().toArray()[1];
System.out.println(s.get(1)); //output is 'medium'
}

find max match count set from multiple set

I am looking for best solution to find matching set with max string match.
Here is example,
inSet = ["a","b","c","x"]
other list of set
set1 = ["a","d","q","s"]
set2 = ["a","m","t","b","z"]
set3 = ["a","x","b","s","r","t"]
in above example, set3 is max. match count (3).
what is best algorithm to find with minimal execution.
any pointer or suggestion appreciated.
Let us have Set<String> set and Guava.Sets:
Set<Set<String>> set = new Set<>();
//add Set<String>s
Set<String> maxMatchSet = set.stream()
.max(Comparator.comparingInt((value -> Sets.intersection(value, inSet).size()))
.get();
OK, now some theory. ["a", "b"] isn't a set but an array (or a list). We have different data structures in Java. Sets are represented in {}.
Anyway, what matters is the code.
Set<String> set = new HashSet<>();
would initialize the Set and
List<String> list = new ArrayList<>();
would initialize the List. Still there is another option:
String[] array = new String[3];
would initialize new array of size 3. Arrays are fixed length.

Add multiple numbered objects to ArrayList

Suppose I have a lot of String Variables(100 for example):
String str1 = "abc";
String str2 = "123";
String str3 = "aaa";
....
String str100 = "zzz";
I want to add these String variables to ArrayList, what I am doing now is
ArrayList<String> list = new ArrayList<String>();
list.add(str1);
list.add(str2);
list.add(str3);
...
list.add(str100);
I am curious, is there a way to use a loop? For example.
for(int i = 1; i <= 100; i++){
list.add(str+i)//something like this?
}
Use an array:
String[] strs = { "abc","123","zzz" };
for(int i = 0; i < strs.length; i++){
list.add(strs[i]); //something like this?
}
This idea is so popular that there's built-in methods to do it. For example:
list.addAll( Arrays.asList(strs) );
will add your array elements to an existing list. Also the Collections class (note the s at the end) has static methods that work for all Collection classes and do not require calling Arrays.asList(). For example:
Collections.addAll( list, strs );
Collections.addAll( list, "Larry", "Moe", "Curly" );
If you just want a list with only the array elements, you can do it on one line:
List<String> list = Arrays.asList( strs );
Edit: Many other classes in the Java API support this addAll() method. It's part of the Collection interface. Other classes like Stack, List, Deque, Queue, Set, and so forth implement Collection and therefore the addAll() method. (Yes some of those are interfaces but they still implement Collection.)
If you are using Java 9 then easily you can add the multiple String Objects into Array List Like
List<String> strings = List.of("abc","123","zzz");
If you want to stick to good practice, declare your Strings in an array:
String[] strs = new String[]{ "abc", "123", "aaa", ... };
for (String s : strs) // Goes through all entries of strs in ascending index order (foreach over array)
list.add(s);
If strX would be class fields then you could try using reflection - link to example of accessing fields and methods.
If it is local variable then you can't get access to its name so you will not be able to do it (unless str would be array, so you could access its values via str[i] but then you probably wouldn't need ArrayList).
Update:
After you updated question and showed that you have 100 variables
String str1 = "abc";
String str2 = "123";
String str3 = "aaa";
//...
String str100 = "zzz";
I must say that you need array. Arrays ware introduced to programming languages precisely to avoid situation you are in now. So instead of declaring 100 separate variables you should use
String[] str = {"abc", "123", "aaa", ... , "zzz"};
and then access values via str[index] where index is value between 0 and size of your array -1, which in you case would be range 0 - 99.
If you would still would need to put all array elements to list you could use
List<String> elements = new ArrayList<>(Arrays.asList(str));
which would first
Arrays.asList(str)
create list backed up by str array (this means that if you do any changes to array it will be reflected in list, and vice-versa, changes done to list from this method would affect str array).
To avoid making list dependant on state of array we can create separate list which would copy elements from earlier list to its own array. We can simply do it by using constructor
new ArrayList<>(Arrays.asList(str));
or we can separate these steps more with
List<String> elements = new ArrayList<>();//empty list
elements.addAll(Arrays.asList(str));//copy all elements from one list to another
Yes. The way to use a loop is not to declare 100 string variables. Use one array instead.
String[] str = new String[101];
str[1] = "abc";
str[2] = "123";
str[3] = "aaa";
....
str[100] = "zzz";
(I made the indexes go from 1 to 100 to show how it corresponds to your original code, but it's more normal to go from 0 to 99 instead, and to initialize it with an array initializer as in #markspace's answer.)
The following creates the ArrayList on the specific String values you have:
ArrayList<String> list1 = new ArrayList<String>() {{addAll(Arrays.asList(new String[]{"99", "bb", "zz"}));}};
Or, if it's just some distinct values you want, use this for say - 10 of them:
ArrayList<String> list2 = new ArrayList<String>() {{for (int i=0; i<10; i++) add(""+System.currentTimeMillis());}};

Java : Create new ArrayLists based on some condition from existing ArrayList

I am new to java .
I have 2 ArrayLists of Strings
List<String> a= [2,14]
List<String> b= [2,3,4,5]
I want two new ArrayLists
1) List has the value which is in b but not in a
List<String> c= [3,4,5]
2) List has the value a but not in b
List<String> d=[14]
I tried:
List<String> c = new ArrayList<String>(b);
c.removeAll(a);
System.out.println("c::::::::::::::::::::::::::::::"+c); // 2,3,4,5
which is not removing the values of List a
Complete Code
public static void updatePartyType(List<String> oldPartyKeys, List<String> newPartyKeys, String customerCode) {
System.out.println("oldPartyKeys--->"+oldPartyKeys);// 2,14
System.out.println("newPartyKeys--->"+newPartyKeys); // 2,3,4,5
System.out.println("oldPartyKeys class --->"+oldPartyKeys.getClass());// class java.util.ArrayList
List<String> newlySelectedPartyKeys = new ArrayList<String>(newPartyKeys);
newlySelectedPartyKeys.removeAll(oldPartyKeys);
System.out.println("newlySelectedPartyKeys::::::::::::::::::::::::::::"+newlySelectedPartyKeys);
You're really proposing set operations more than list operations - in which case you'd be better off using a HashSet than an ArrayList. Then you could use Collection<E>.removeAll:
Set<String> a = ...;
Set<String> b = ...;
Set<String> c = new HashSet<String>(b);
c.removeAll(a);
Set<String> d = new HashSet<String>(a);
d.removeAll(b);
(This will work for ArrayList as well as HashSet - I've only changed to using sets because it's a more appropriate type when you want set-based operations.)
Or better, use Guava's Sets.difference method:
Set<String> a = ...;
Set<String> b = ...;
Set<String> c = Sets.difference(b, a);
Set<String> d = Sets.difference(a, b);
This will create views on the differences - so changes to the original sets will be reflected in the views. You can effectively take a snapshot of a view by creating a new HashSet:
Set<String> snapshot = new HashSet<String>(c);
This can be done by using the removeAll method:
List<String> c = new ArrayList<>(b);
c.removeAll(a);
List<String> d = new ArrayList<>(a);
d.removeAll(b);
take a look at the addAll() and removeAll() in ArrayList
now you need b\a which is b.removeAll(a)
and a\b which is a.removeAll(b)
A working example (this is for those who are new to Java, so it's verbose):
public static void main(String[] args) {
// first we want to create the lists
// create list a
List<String> a = new ArrayList<String>();
// add members to a
a.add("2");
a.add("14");
// create list b
List<String> b = new ArrayList<String>();
// add members to b
b.add("2");
b.add("3");
b.add("4");
b.add("5");
// create a list in which we store the "filtered" list - duplicated from
// a
List<String> aMinusB = new ArrayList<>(a);
// "filter" using "removeAll" and giving the list b as the argument
aMinusB.removeAll(b);
System.out.println("A minus b:");
// this is short for
// "iterate over the entire list, naming the currently iterated node s"
for (String s : aMinusB) {
System.out.println(s);
}
// duplicate list b in the same manner as above
List<String> bMinusA = new ArrayList<>(b);
// "filter" using "removeAll" and giving the list a as the argument in
// the same manner as above
bMinusA.removeAll(a);
System.out.println("B minus a:");
// this is short for
// "iterate over the entire list, naming the currently iterated node s"
// in the same manner as above
for (String s : bMinusA) {
System.out.println(s);
}
}
Convert your lists to Set instances. Then you can easily find the difference of sets by your own implementation or using a 3rd party library like Google Guava which has Sets.difference(), for example.
addAll elements, then removeAll elements that appears in a.
The time complexity is O(n).

How to populate a List with a while loop without declaring a new object every time?

So, I'm trying to s a list of documents that contain a term and then enter the corresponding document_id and the term frequency into an array (of size 2). I then add this entry array into a List, so that the final List contains an all the entries. However, because the entry is passed by reference into the List, I have no idea how to accomplish this, since it rewrites itself every time. And due to the size of the data, my program runs out of memory if I try to declare a new int[] entry within the while loop. Any ideas on how to get pass this? I'm a but rusty on my Java. Thanks.
List<int[]> occurenceIndex = new ArrayList<>();
int[] entry = new int[2];
while (matchedDocs.next())
{
entry[0] = (matchedDocs.doc()); // Adds document id
entry[1] = (matchedDocs.freq()); // Adds term weight
occurenceIndex.add(entry);
}
Try to create a new object of the int array inside the loop.
List<int[]> occurenceIndex = new ArrayList<>();
while (matchedDocs.next())
{
int[] entry = new int[2];
entry[0] = (matchedDocs.doc()); // Adds document id
entry[1] = (matchedDocs.freq()); // Adds term weight
occurenceIndex.add(entry);
}
You have to put int[] entry = new int[2]; into the while loop
does it need to be an int, what about byte or short? if this isn't possible then the program needs to be re-factored as there is no way to store the arrays like this using the same array instance. – Neil Locketz 1 min ago edit
Consider using HashMap to store records.
Map<Integer, Integer> occurenceIdx = new HashMap<Integer, Integer>();
while(matchedDocs.next())
occurenceIdx.put(matchedDocs.doc(), matchedDocs.freq());
That's all the code you need to create the map. To retrieve value based on doc ID
docFreq = occurenceIdx.get(docId);
Please note that this will work ONLY if you have unique doc IDs. If not, you will have to improvise on this solution. I would probably make my map a HashMap<Integer, List<Integer>> to support multiple instances of docID

Categories

Resources