This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 4 years ago.
How can I update the only str2 by not really updating str1 and str? Why is the change in str2 is updating str1 and str? Is it because of the object reference?
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class test {
List<HashMap<String, String>> str;
public static void main(String[] args) {
Map<String, String> hmap = new HashMap<String, String>();
hmap.put("1", "s1");
hmap.put("2", "s2");
test testobj = new test();
testobj.str = new ArrayList<HashMap<String, String>>();
testobj.str.add((HashMap<String, String>) hmap);
testing(testobj.str);
}
static void testing(List<HashMap<String, String>> str) {
List<HashMap<String, String>> str2 = new ArrayList<HashMap<String, String>>();
List<HashMap<String, String>> str1 = str;
str2.add(str1.get(0));
str2.get(0).put("1", "new");
System.out.println(str);
System.out.println(str1);
System.out.println(str2);
}
}
You have to create a copy of the original List like this:
List<HashMap<String, String>> str1 = new ArrayList<>(str);
which creates a new ArrayList containing all the elements from the original List. This way you'll have two separate list containing its own elements.
Related
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 1 year ago.
Improve this question
I have a list of maps
List<Map<String, Object>> myList = [{value1=3, value2=11},{value1=8, value2=16},{value1=3, value2=11},{value1=10, value2=11} ...]
and I want to extract value2 to a new list of maps but have only unique values there:
List<Map<String, Object>> res = [{value2=11},{value2=16} ...]
What id the best way to do it?
Try this. Here first I am creating a list of Entry<value2, anyUniqueValue> by using 2 functions.
First filtering only those Entries which has key value2 by using function filterFunction
Secondly by filtering unique value by using function distinctByValue
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class Demo{
public static void main(String[] args) {
List<Map<String, Object>> myList = new ArrayList<>();
Map<String, Object> map1 = new HashMap<>();
map1.put("value1", 3);
map1.put("value2", 11);
Map<String, Object> map2 = new HashMap<>();
map2.put("value1", 8);
map2.put("value2", 16);
Map<String, Object> map3 = new HashMap<>();
map3.put("value1", 3);
map3.put("value2", 11);
Map<String, Object> map4 = new HashMap<>();
map4.put("value1", 10);
map4.put("value2", 11);
myList.add(map1);
myList.add(map2);
myList.add(map3);
myList.add(map4);
List<Entry<String, Object>> list = myList.stream().flatMap(map -> map.entrySet().stream())
.filter(s -> filterFuction(s)).filter(distinctByValue(entry -> entry.getValue()))
.collect(Collectors.toList());
List<Map<String, Object>> list1 = list.stream().map(t -> {
Map<String, Object> map = new HashMap<>();
map.put(t.getKey(), t.getValue());
return map;
}).collect(Collectors.toList());
System.out.println(list1);
}
public static <T> Predicate<T> distinctByValue(Function<? super T, ?> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
public static boolean filterFuction(Entry<String, Object> entry) {
if (entry.getKey().equals("value2"))
return true;
return false;
}
}
This question already has answers here:
What does it mean to "program to an interface"?
(33 answers)
Closed 3 years ago.
Now I got a dictionary like this
Dictionary dict = new Hashtable();
dict.put("shipno", item.getShipNumber());
dict.put("addr", item.getFinalAddr());
dict.put("receiver", item.getReceiverName());
dict.put("phone", item.getReceiverPhone());
and I'm going to pass this dictionary to funcion Test() as a parameter, what should I put in the '()'
public static int Test(Dictionary)
Is this correct? Thanks!
In your code you have to call this method:
Dictionary dict = new Hashtable();
dict.put("shipno", item.getShipNumber());
// CAll THIS METHOD
Test(dict);
And in your method you can get this data:
// YOUR METHOD, where "dict" is passed argument/parameter
public static int Test(Dictionary dict) {
}
Its working here
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;
public class Dict {
public static void main(String[] args) {
Dictionary<String, String> obj = new Hashtable<String, String>();
obj.put("Hello", "World");
obj.put("Hello1", "World3");
obj.put("Hello2", "World32");
Dict ca = new Dict();
ca.test(obj);
}
public void test(Dictionary<String, String> obj) {
Enumeration<String> enumData = obj.elements();
while (enumData.hasMoreElements()) {
System.out.println(enumData.nextElement());
}
}
}
I have a hashMap with the following declaration:
Map<String, Integer> terms = new HashMap<>();
and a List as follow:
List<String> allTerms = new ArrayList<>();
The hashMap and the List contain Strings.
I want to remove all Strings stored in the hashMap not listed in the declared List.
What is the better way to do that?
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test {
static boolean match = true;
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
Map<String, Integer> map1 = new HashMap<String, Integer>();
List<String> list = Arrays.asList("Test1", "Test2", "Test3", "Test4", "Test5", "Test6", "Test7");
map.put("Test1", 1);
map.put("Test66", 2);
map.put("Test3", 3);
map.put("Test4", 4);
map.put("Test123", 5);
map.forEach((k, v) -> {
match = false;
list.forEach(s -> {
if (k.equals(s))
match = true;
});
if(match)
map1.put(k,v);
});
map = map1;
map.forEach((k,v)->System.out.println(k));
}
}
Output:
Test1
Test4
Test3
I've been having this error where this class(DataProvider) for my project that I just created will not seem to accept .add or .put. But my MainActivity class accepts them just fine. I’ve already done the Invalidate Caches and Restart. Can someone explain to me why this is happening and what I can do to fix it?
DataProvider:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class DataProvider {
public static HashMap<String, List<String>> getInfo()
HashMap<String, List<String>> MoviesDetails = new HashMap<String, List<String>>();
List<String> Action_Movies = new ArrayList<String>();
//'.add' would be an error in red. Cannot resolve symbol 'add'.
Action_Movies.add("");
List<String> Romantic_Movies = new ArrayList<String>();
Romantic_Movies.add("");
List<String> Horror_Movies = new ArrayList<String>();
Horror_Movies.add("");
List<String> Comedy_Movies = new ArrayList<String>();
Comedy_Movies.add("");
}
MainActivity:
import android.app.Activity;
import android.os.Bundle;
import android.widget.ExpandableListView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends Activity {
HashMap<String, List<String>> Movies_categories;
List<String> Movies_list;
ExpandableListView Exp_list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<String> Test = new ArrayList<String>();
Test.add("Test");
}
}
You are missing a semicolon at the end of this line:
public static HashMap<String, List<String>> getInfo()
Which makes the code analysed go crazy and not see your objects correctly as their types. Just add the semicolon.
Also, you will probably want to remove the parenthesis at the end of the line, as it suggests it it a method. So do something like this:
public static HashMap<String, List<String>> getInfo;
Or this:
public static HashMap<String, List<String>> getInfo(){
//Some actual code here, which returns a HashMap
};
Now I see that your whole class tructure is messed up. Try the below code:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class DataProvider {
public static HashMap<String, List<String>> getInfo;
public DataProvider() {
HashMap<String, List<String>> MoviesDetails = new HashMap<String, List<String>>();
List<String> Action_Movies = new ArrayList<String>();
Action_Movies.add("");
List<String> Romantic_Movies = new ArrayList<String>();
Romantic_Movies.add("");
List<String> Horror_Movies = new ArrayList<String>();
Horror_Movies.add("");
List<String> Comedy_Movies = new ArrayList<String>();
Comedy_Movies.add("");
}
}
On another side note, consider creating your variables outside of the constructor and initializing them inside the constructor.
public class DataProvider {
public static HashMap<String, List<String>> getInfo;
HashMap<String, List<String>> movieDetails;
List<String> actionMovies;
List<String> romanticMovies;
List<String> horrorMovies;
List<String> comedyMovies;
public DataProvider() {
movieDetails = new HashMap<String, List<String>>();
actionMovies = new ArrayList<String>();
actionMovies.add("");
romanticMovies = new ArrayList<String>();
romanticMovies.add("");
horrorMovies = new ArrayList<String>();
horrorMovies.add("");
comedyMovies = new ArrayList<String>();
comedyMovies.add("");
}
}
These lines may have been added inside the class but outside the constructor or method. Make sure the instructions are within a method.
I have 1 object(Goods) have 2 attributes: String and boolean. How to input object Goods to ArrayList<HashMap<String, Object>> ? Because I want input ArrayList<HashMap<String, Object>> to SimpleAdapter
public class Goods {
private String goodsName;
private boolean isCheck = false;
public String getGoodsName() {
return goodsName;
}
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
public boolean isCheck() {
return isCheck;
}
public void setCheck(boolean isCheck) {
this.isCheck = isCheck;
}
}
package ngo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Goods g = new Goods();
g.setGoodsName("foo");
g.setCheck(true);
Map<String, Goods> map = new HashMap<String, Goods>();
map.put(g.getGoodsName(), g);
List<Map<String, Goods>> list = new ArrayList<Map<String, Goods>>();
list.add(map);
System.out.println(list.get(0).get("foo").isCheck());
}
}
Displays true
This should be an acceptable, if simple, structure for the data parameter of SimpleAdapter's constructor. A more exhaustive example of it's use can be found here
The following is the basic example, not runnable in itself.
ArrayList<HashMap<String, Goods>> listOfMappedGoods = new ArrayList<HashMap<String, Goods>>();
HashMap<String, Goods> goodsList = new HashMap<String, Goods>();
Goods g = new Goods();
g.setGoodsName("foo");
g.setCheck(true);
goodsList.add(g.getGoodsName(), g);
listOfMappedGoods.add(goodsList);
The point to note, is that just like every new Goods object needs to be created using new Goods(), each new goodsList needs to be created also using new HashMap<String, Goods>().
If you use something like goodsList.clear(), then you are still referring to the original map that was first added to the listOfMappedGoods, so you will clear that instead.