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());
Related
This question already has answers here:
Split a list into sublists based on a condition with Stream api
(8 answers)
Closed 1 year ago.
I need to create 2 lists based on a predicate by using stream().reduce(). I got a similar code but it's not working.
localRequestDTOList.stream().reduce((res, item) ->{
res[predicate(item) ? 'a' : 'b'].push(item);
return res;
}, { a: [], b: [] });
The predicate is shown below.
public static Predicate<LocalRequestDTO> payToVendor() {
return request -> (request.getSuffix().equals("00"));
}
What I want is from localRequestDTOList create two lists with the condition that their request.getsuffix().equals("00") or not. I simply put the two lists as a and b.
You asked about how to partition a list by using reduce. That's like asking how to hammer a nail using a screwdriver. It would be better to use the correct method for the purpose.
If you can use collect() then you could make use of Collectors.partitioningBy():
Map<Boolean, List<LocalRequestDTO>> partition = localRequestDTOList.stream()
.collect(Collectors.partitioningBy(payToVendor()));
List<LocalRequestDTO> a = partition.get(true);
List<LocalRequestDTO> b = partition.get(false);
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/
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:
Iteratively compute the Cartesian product of an arbitrary number of sets
(10 answers)
Closed 6 years ago.
I want to generate permutations of multiple lists of different types. Let me put an example as explaining it in english would be tough.
Class Rule {
private List<Long> ids;
private List<String> names;
private List<ABCEnum> enums;
}
I want to generate permutations in form of output objects which looks like this:
Class Output {
Long id;
String name;
ABCEnum enum
}
Test Example-
Input--
Rule:
ids -- 1,2
names -- abc,bcd
enums -- NEW,OLD
Generated Output objects: ( total -- 2 * 2 * 2 = 8 objects)
1,abc,NEW
1,bcd,NEW
1,abc,OLD
1,bcd,OLD
2,abc,NEW
2,bcd,NEW
2,abc,OLD
2,bcd,OLD
Things I have tried:
tried to map permutations of a string example to my problem with no luck.
I can go into for loops but that is not a good solution.
Please let me know if more information is needed.
Any help in solving this is greatly appreciated.
Thanks
for (Long id : ids)
for (ABCEnum e : enums)
for (String name : names)
System.out.println(id + "," + name + "," + e);
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();