so i'm working on a project and i need the following to work:
Let's say I have a String[] contatining out of f.e 3 values "0D", "0A", "01A0"
Now in the background I got like a defined description for each of these values and I want to show them in another string.
So in the end i want to call a method with String"0D" and the method returns me the description, in this example "speed"
same for the others, if i call the method with "0A" it returns String "Fuel Pressure"
Is there an efficient way for achieving this? Cause i've got a pretty long list and don't want to manually input all the descriptions to the commands..
Yeah a HashMap would work.
You could try this:
HashMap<String, String> valueDescription = new HashMap<>();
valueDescription.put("0D", "speed");
valueDescription.put("0A", "Fuel Pressure");
valueDescription.put("01A0", "Temperature");
public String getDescription(String value) {
if (valueDescription.containsKey(value)) {
return valueDescription.get(value);
} else {
return "Description not found";
}
}
I would consider using a hashmap of <String, String>. The key would be the command, and the value is the description.
Related
I have some inputted String String usrInput; that user could import some string once into App without any case-sensitivity policy like: "start","Start","START","end" ,"END" and etc.
And I have a Map that i inserted my strings for example "start" into that and put it into HashMap<String, String> myMap:
Map<String, String> listOfActions = new HashMap<>();
listOfActions.put(myStr, myStr);
Now I want to check listOfActions members to get for example "start" filed in every case model ("start","Start","START") , currently I do like below:
if (listOfActions.containsKey(usrInput.toUpperCase())
|| listOfActions.containsKey(usrInput.toLowerCase())) {
/// some do
}
So I want to know:
1. Is there any way to get String value without case-sensitivity?
I will also add this here I couldn't use equalsIgnoreCase() method for get items from Map because its return Boolean.
2. I have similar problem in switch-case statements to check 2 string equality without case-sensitivity.
You can use
Map<String, String> listOfActions = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
Other solutions can be Apache's CaseInsensitiveMap or Spring's LinkedCaseInsensitiveMap.
Please see https://www.baeldung.com/java-map-with-case-insensitive-keys for more details about these solutions.
If you only use inputs as map keys (i.e. you don't need to later reproduce the strings in original casing), I suggest just lowercasing all inputs before inserting them into the map:
Map<String, String> listOfActions = new HashMap<>();
listOfActions.put(myStr.toLowerCase(), myStr);
This will simplify locating the values later on, since you know that all keys are already lowercased, so the lookup becomes easy:
if (listOfActions.containsKey(myStr.toLowerCase())) {
// do something
}
When you create a new instance of HashMap, you can override some of its methods, such as put and containsKey like this:
Map<String, String> map = new HashMap<>() {
#Override
public String put(String key, String value) {
return super.put(key.toLowerCase(), value);
}
#Override
public boolean containsKey(Object key) {
return super.containsKey(key.toString().toLowerCase());
}
};
map.put("START", "doStart");
System.out.println(map); // {start=doStart}
System.out.println(map.containsKey("START")); // true
System.out.println(map.containsKey("Start")); // true
System.out.println(map.containsKey("start")); // true
One thing you can do is make everything upper-case or lower-case, then compare them.
string.toLowerCase().equals("other string");
string.toUpperCase().equals("OTHERSTRING");
This way, whether it is lower-case or upper-case, it will only be compared as one or the other, and acts as though it were case insensitive.
I have a class Agent, which has following members:
class Agent{
String name;
long funds;
//... getters and setters, parameterized constructor
}
Now, I have a list of Agent class objects.
ArrayList<Agent> listAgents=new ArrayList<Agent>();
I want to give stars to the top performers, like 5 star for someone who has funds of more than 100000, 4 stars to someone with fund of 80000, and so on.
I want to store this record in Map<String,String> like
<ABC,*****> <PQR,****>
I tried the following code:
Map<String,String> star=listAgents
.stream()
.collect(Collectors.groupingBy(agn->giveStars(agn.getGeneratedFund())));
Here giveStars is function defined as below:
public static String giveStars(long generatedFund) {
if(generatedFund>=100000)
return "*****";
else if(generatedFund<100000&& generatedFund>=80000)
return "****";
else if(generatedFund<80000 && generatedFund>=60000)
return "***";
return "";
}
This didn't work. Also, I don't think this is the right way to do this.
How to do this using Stream API's functions?
Any help would be appreciated. Thanks in advance.
Assuming <ABC,*****> <PQR,****> means you have a map of agent name to its star rating, you don't want grouping, you want to map your existing items to different ones.
Here's one way how:
Map<String,String> star = listAgents.stream()
.collect(Collectors.toMap(Agent::getName, agn->giveStars(agn.getGeneratedFund())));
If you group items, you don't change them but assign to different groups (doh). Mapping is a process where you change an object to be something different.
First, there is an issue in the method giveStars which should be rewritten:
public static String giveStars(long generatedFund) {
if (generatedFund >= 1_000_000)
return "*****";
else if (generatedFund >=800_000)
return "****";
else if (generatedFund >= 600_000)
return "***";
return "";
}
Next, the code Collectors.groupingBy(agn->giveStars(agn.getGeneratedFund())) contradicts the intention to have a map Map<String, String> - it will create Map<String, List<Agent>> where the key is the star rating. So maybe your real intention is to change the type of the map.
Map<String, List<Agent>> groupByStars = listAgents.stream()
.collect(Collectors.groupingBy(agent -> giveStars(agent.getGeneratedFund())));
Such map will let to get top agents immediately.
If Map<String, String> (agent name to stars rating) is required, toMap collector may be used as suggested earlier, but this would work only if agent names are unique. If some duplicate values may occur, a merge function is required (e.g. to keep the agent with a better rating):
Map<String, String> groupByAgentName = listAgents.stream()
.collect(Collectors.toMap(
Agent::getName,
agent -> giveStars(agent.getGeneratedFund()),
(rating1, rating2) -> rating1.length() > rating2.length() ? rating1 : rating2,
LinkedHashMap::new // keep insertion order
));
I am trying to add FullTextFilters to my FullTextQuery in hibernate and there is only the method FullTextFilter.setParameter(String name, Object value)
I am trying to make a flexible, generic function to add filters to the query based on the entity its searching for, some have one parameter, some have two for their filters, so I would like to add a method to FullTextFilterImpl; setParameters(String[] names, String[] value) where I can pass in the names of all the parameters and probably a multidimensional array of the values for each parameter to transform my current code of
If( "checking which entity it is"){
fullTextQuery.enableFullTextFilter("FilterName").setParameter("firstFilter", "val1").setParameter("secondFilter", "val2");
}
else if("this entity's filter only has one parameter"){
fullTextQuery.enableFullTextFilter("FilterName").setParameter("firstFilter", "val1");
}
I tried creating a subclass of FullTextFilterImpl and putting a setParameters function in it, but the way this code is set up I'm not sure how to utilize it as FullTextQuery.enableFullTextFilter(filterName) returns a FullTextFilter object and then you call the setParameter() on that object. I'm not sure how I would get in the middle of that to do a setParameters
EDIT: I have downloaded the hibernate-search source code and added the following method to FullTextFilterImpl which I think will do what I want, but when I go to build it (even just the out-of-the-box project) I get all these checkstyle Only one new line is allowed at the end of a file errors. Is there something I'm missing from the hibernate quick-build guide.
public FullTextFilter setParameters(Map<String, List<String>> params){
for (String key : params.keySet()) {
List<String> values = params.get(key);
for(int i=0; i< values.size() ; i++){
parameters.put(key, values.get(i));
}
}
return this;
}
You can easily pass a Map of attributes to your custom Filter, the signature is:
FullTextFilter setParameter(String name, Object value);
so you could do
filter.setParameter( "myMap", properties );
where properties is an hashmap.
About the compilation error message:
Only one new line is allowed at the end of a file
is a message from checkstyle, it verifies code style is conforming to the Hibernate code style.
It's very simple to fix: there are multiple empty lines at the end of the source file, delete them. The error message should tell you what file needs to be polished.
if i correctly understand you question you need Builder pattern
here an example you could use :
public class FullTextFilter {
String[] keys;
Object[] objects;
private FullTextFilter(String[] keys, Object[] objects) {
}
public static FullTextFilterBuilder builder(){
return new FullTextFilterBuilder();
}
public static class FullTextFilterBuilder {
private Map<String, Object> parameters = new HashMap<String, Object>();
public FullTextFilterBuilder setParameter(String key, Object value){
parameters.put(key, value);
return this;
}
public FullTextFilter build(){
return new FullTextFilter(parameters.keySet().toArray(new String[0]), parameters.values().toArray(new Object[0]));
}
}
}
and then using it like this :
FullTextFilter filter = FullTextFilter.builder().setParameter("", new Object()).setParameter("", new Object()).build();
tell if that's what you are looking for.
if not i'll delete my answer
I presume you want this:
fullTextQuery.enableFullTextFilter("FilterName").setParameter("firstFilter", "val1").setParameter("secondFilter", "val2");
fullTextQuery{
name:"FilterName"
,parameters:["filter1":"value1", "filter2":"value2"]
}
static FullTextQuery enableFullTextFilter(String name){...}
FullTextQuery setParameter(String key, String value){
parameters.put(key, value);
return this;
}
assuming a parameters hashmap.
seeing as I was a little off base.. cant you do something like this?
setFilters (HashMap<String, String> filters) {
FullTTextFilter fl = FullTextQuery.enableFullTextFilter("filtername");
for (String key : filters.keySet()) {
fl.setParameter(key, filters.get(key));
}
}
Hi I have a strange question about java. I will leave out the background info so as not to complicate it. If you have a variable named fname. And say you have a function returning a String that is "fname". Is there a way to say reference the identifier fname via the String "fname". The idea would be something like "fname".toIdentifier() = value but obviously toIdentifier isn't a real method.
I suppose a bit of background mite help. Basically I have a string "fname" mapped to another string "the value of fname". And I want a way to quickly say the variable fname = the value of the key "fname" from the map. I'm getting the key value pair from iterating over a map of cookies in the form . And I don't want to do "if key = "fname" set fname to "value of fname" because I have a ton of variables that need to be set that way. I'd rather do something like currentkey.toIdentifer = thevalue. Weird question maybe I'm overlooking a much easier way to approach this.
Why don't you just use a simple hashmap for this?
Map<String, String> mapping = new HashMap<String, String>();
mapping.put("fname", "someValue");
...
String value = mapping.get(key); //key could be "fname"
In a way you're describing what reflection is used for:
You refer to an object's fields and methods by name.
Java Reflection
However, most of the time when people ask a question like this, they're better off solving their problem by re-working their design and taking advantage of data structures like Maps.
Here's some code that shows how to create a Map from two arrays:
String[] keyArray = { "one", "two", "three" };
String[] valArray = { "foo", "bar", "bazzz" };
// create a new HashMap that maps Strings to Strings
Map<String, String> exampleMap = new HashMap<String, String>();
// create a map from the two arrays above
for (int i = 0; i < keyArray.length; i++) {
String theKey = keyArray[i];
String theVal = valArray[i];
exampleMap.put(theKey, theVal);
}
// print the contents of our new map
for (String loopKey : exampleMap.keySet()) {
String loopVal = exampleMap.get(loopKey);
System.out.println(loopKey + ": " + loopVal);
}
Here's a link to the JavaDoc for Map.
I need to search through a HashMap that contains a key/value of either String, ArrayList<Users> or String, HashSet<Users> for a given value. I am unsure how to write the code to do this in java.
I declared..
private HashMap<String, ArrayList<Users>> cm = new HashMap<>();
my method that needs to be called to search looks like this...
public void doSomething(User u, String product) {
}
so I'm unsure of how the code inside the method would work.
if (cm.containsKey(product) {
//This is where I'm unsure if I find the key on how to check if the ArrayList has a
particular user. And then if not how to add them.
}
Your User addition method could look like this:
public void doSomething(User user, String product) {
if (cm.containsKey(product)) {
List<User> list = cm.get(product);
if (!list.contains(user)) {
list.add(user);
}
}
}
This assumes that you define your HashMap with a single User type:
HashMap<String, ArrayList<User>> cm = new HashMap<>();
I'm not sure exactly how to do it, but I asked a question a few days ago concerning map entry sets and using '?' to allow multiple types. The answer I accepted was well explained and comes with an example. Might help you out.
Trouble understanding Java map Entry sets