This question already has answers here:
get string value from HashMap depending on key name
(10 answers)
Closed 3 years ago.
Could someone tell me how to get or print the String value of a map element?
The below code results in "The method values() is undefined for the type String."
I also tried .getValue() but the outcome is the same.
Thanks in advance!
Map<Integer, String> mapName = new HashMap<>();
mapName.put(0, "description_0");
mapName.put(1, "description_1");
for (Integer i : mapName.keySet()){
System.out.println(mapName.get(i).values());
}
Answer provided by #Lino.
for(String s : mapName.values()) System.out.println(s);
If you want to use stream:
mapName.entrySet().stream().forEach(elem-> System.out.println(elem));
This will allow you to use all the features of stream such as filtering,collecting , reducing etc.
https://www.geeksforgeeks.org/stream-map-java-examples/
Related
This question already has answers here:
How to get the enum type by its attribute?
(11 answers)
Can I get an enum based on the value of its field?
(4 answers)
Get enum by its inner field
(5 answers)
Closed 3 years ago.
I have an enum with custom values:
enum DaysOfExercise{
MONDAY ("legs Workout"),
WEDNESDAY ("back workout"),
SATURDAY ("running") ;
private String exercise ;
private DaysOfExercise(String exercise){
this.exercise = exercise ;
}
public String getExercise(){
return this.exercise ;
}
}
I need to add a search feature that returns a DaysOfExercise based on an entered exercise name.
I know that there is is the .values() method in the Enum to return the list of DaysOfExercise values to easily iterate over, but in my case I want to return the embedded values list to compare with what the user has typed in.
Is there any built-in method that could return the list of the enum custom values instead of the enum values?
Note: It is not that I'm stuck with this problem. I can easily solve it with a couple of loops. I'm just looking for an optimized solution.
Use a stream to map an array of enum values to a list of strings.
List<String> exercises = Stream.of(DaysOfExercise.values())
.map(DaysOfExercise::getExercise)
.collect(Collectors.toList());
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 5 years ago.
I'm facing a problem using ArrayList. I'm using an ArrayList with this content :
String, int, HashTable, HashTable
The HashTables are formed with a String key and an int value.
At some point in my program I need to set the value of the two HashTable. If I set ArrayList(2) (so first hashtable) with a HashTable h_gain for example and then I clear h_gain, the value assigned before with the right content is set to null (cause h_gain is now empty).
a_j1.set(2, h_gain);
Hashtable<String, Integer> h_tmp2 = (Hashtable<String, Integer>) a_j1.get(2);
// Gives the right value - like 1000 for example
System.out.println("TESSSSSSSSSSSSSST " + h_tmp2.get("En plein"));
h_gain.clear();
// Gives me null
h_tmp2 = (Hashtable<String, Integer>) a_j1.get(2);
System.out.println("TESSSSSSSSSSSSSST " + h_tmp2.get("En plein"));
I don't get why it acts like this. If I simply do it with a variable the behavior is more like expected
int val1 = 10
int val2 = val1 // val2 = 10
val1 = 0 // Well, val2 is still = 10
Any help on this?
I think I can answer this question for you.
You might think that there is another object inside your ArrayList after the insert but that is actually not the truth.
The object h_gain is referenced in your a_j1.
By clearing h_gain you also clear the object in a_j1 cause this is only a reference. When you have to clear h_gain I would recommend to clone/copy your object before inserting it into a_j1.
So try this:
a_j1.set(2, h_gain.clone());
Hashtable<String, Integer> h_tmp2 = (Hashtable<String, Integer>) a_j1.get(2);
System.out.println("TESSSSSSSSSSSSSST " + h_tmp2.get("En plein"));
h_gain.clear();
h_tmp2 = (Hashtable<String, Integer>) a_j1.get(2);
System.out.println("TESSSSSSSSSSSSSST " + h_tmp2.get("En plein"));
The difference is, that Java do not insert a reference of the old object but the reference of the new cloned object which (indeed) is not changed anymore. And that is the reason why you now can change the old value.
This question already has answers here:
How to convert HashMap to json Array in android?
(5 answers)
Closed 5 years ago.
I am developing an Android app in which I have to send LinkedHashMap results by API but the problem what I am getting is format of result is different. How can I put keys and values both in inverted commas?
I'm getting result like this:
list: {0=816444014066, 1=747083010945, 2=816444010969}
And I want result like this:
list: {"0" : "816444014066","1" : "747083010945","2" : "816444010969"}
How to change the format of result?
Use My Answer. It worked for me.
LinkedHashMap<String, String> data = new LinkedHashMap<String, String>();
// Instantiate a new Gson instance.
Gson gson = new Gson();
// Convert the ordered map into an ordered string.
String json = gson.toJson(data, LinkedHashMap.class);
// Print ordered string.
Log.e("list", ""+json); // {"0" : "816444014066","1" : "747083010945","2" : "816444010969"}
To get the quotes you need to make your keys and values String in your LinkedHashMap
Edit:
maybe what you need is already provided in this answer
In Java you can put quotes to String with :
String value = " \"1\" ";
You could do it like this:
Map<String, String> linkedmap = new LinkedHashMap<>();
linkedHashMap.put(setQuotes("1"), setQuotes("5445454"));
public static String setQuotes(String value){
String result = "";
if(!value.isEmpty()){
result = "\"" + value + "\"";
}
return result;
}
If you print it in the console, it returns:
{"1"="5445454"}
I think that possibility is to create your own Map class that extends LinkedHashMap and to create and implement in it method with behavior similar to behavior of toString() method. This link might help you to get started with implementation of that method:
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/AbstractMap.java#AbstractMap.toString%28%29
This question already has an answer here:
Type mismatch: cannot convert from int to boolean in while loop
(1 answer)
Closed 6 years ago.
I get two dates from a request object using stream filter. There I have to compare those objects then collect them store in list. But now i get this error. Please help me with it.
Error:
Type mismatch: cannot convert from int to boolean
Code:
Date checkIn = req.getCheckIn();
Date checkOut = req.getCheckOut();
List<PlaceBook> filtered = checkInVal.stream().filter(string ->
string.getCheckInDt().compareTo(checkIn)).collect(Collectors.toList());
You dont declare what your filter condition actually is:
List<PlaceBook> filtered = checkInVal.stream().filter(string ->
string.getCheckInDt().compareTo(checkIn) == 0 /* == 0, for example is missing*/).collect(Collectors.toList());
compareTo by itself returns an int value, that cannot be cast to boolean, which is required by filter.
BTW 'string' is not a good name in the filter.
This question already has answers here:
Java Reflection: How to get the name of a variable?
(8 answers)
Closed 3 years ago.
I'm using a ContentResolver query to get some data from a database in Android. That's not the issue.
The method returns string representation of integers,
INT TYPE_MAIN = 2
I want to convert that to a string Type_Main
String a = someMagicalMethod(TYPE_MAIN);
System.out.println(a);
Such that the output would be
TYPE_MAIN
I can't use Integer.toString(TYPE_MAIN) because that would return the value of it which is 2
How can I achieve this?
In Java, you cannot inspect values of variables by using their name, that info is not available at run time, not even through reflection. Use a Map<String, Integer> to solve your problem:
Map<String, Integer> map = new HashMap<>();
map.put("TYPE_MAIN", 2);
//...
String a = map.get("TYPE_MAIN").toString(); //someMagicalMethod(TYPE_MAIN);
System.out.println(a); //prints 2
Make it an Enum, then you can use String a = TYPE_MAIN.getName();