Java Enum group enums by their values - java

Can you help me with solving some thing. I have enum in my java application:
public enum EnumKey {
ALPHA("group1"),
BETA("group2"),
GAMMA("group3"),
SIGMA("group2"),
DELTA("group2")
// and other values with "group1" or "group2" or "group3", constructors and getters
private String groupName;
}
I want to get something like Map<String, List<EnumKey>>, where keys is my specified groupNames and values is groupped and sorted by groupName enumKey list(I have only three specified groupNames). I hope my question is clear.
Hope you will help me to find an elegant way to do this.

This should generate the map you need:
public static Map<String, List<EnumKey>> crateEnumKeyMap() {
Map<String, List<EnumKey>> map = new HashMap<>();
for (EnumKey enumKey : EnumKey.values()) {
List<EnumKey> enumKeyList = map.get(enumKey.getGroupName());
if (enumKeyList == null) {
enumKeyList = new ArrayList<>();
map.put(enumKey.groupName, enumKeyList);
}
enumKeyList.add(enumKey);
}
return map;
}

Just create a map inside your EnumKey with the signature you yourself suggested.
In a static code block iterate over all the values in the enum and add them to the map by adding them to the appropriate list if it exists, if not creating the list and then adding it.

Related

fill an HashMap with elements of a set passed as parameter

i have to write the method:
public Map<Robot, Integer> PickedUpForEachRobot(Set<Stuff> pickedUp)
which has to iterate through the set passed as parameter and has to count the quantity of stuff picked up by each robot and associate it to his instance.
what i have done is this:
public Map<Robot, Integer> PickedUpForEachRobot(Set<Stuff> pickedUp) {
final Map<Robot,Integer> map = new HashMap<>();
for(Stuff stuff : pickedUp){
Integer quantity = map.get(stuff.getPicker());
if(quantity!=null){
map.put(stuff.getPicker(), quantity);
}
}
return map;
}
I also have other classes:
public class Stuff {
private Robot picker;
public Robot getPicker() {
return this.picker;
}
}
and:
public class Robot {
private Set<Stuff> bunchOfStuff;
public Set<Stuff> getBunchOfStuff() {
return this.bunchOfStuff;
}
}
for which i have tried to be synthetic, so i hope i can be clear anyway.
So my problem is that when i do a test for this method:
#Test
public void testRaccoltoPerMezzo() {
Statistics stats = new Statistics();
Stuff stuff1 = new ball();
Stuff stuff2 = new legoPiece();
Set<Stuff> set = new HashSet<>();
set.add(stuff1);
assertEquals(1,set.size());
Map<Robot,Integer> map = new HashMap<>();
map.put(stuff1.getPicker(),1);
assertEquals(map, stats.PickedUpForEachRobot(set));
}
it fails and it says to me:
java.lang.AssertionError: expected:<{null=1}> but was:<{}>
and i can't understand why. Can somebody help me?
This message :
java.lang.AssertionError: expected:<{null=1}> but was:<{}>
means that you expect to have a map with one element that owns a null key and as associated value 1 but you got a empty map.
The expected map you have created doesn't seem to be adequate according to your requirement and the actual map either.
About the populating of the map in the implementation, I noticed at least this point that is not at all logical.
Here :
final Map<Robot,Integer> map = new HashMap<>();
for(Stuff stuff : pickedUp){
Integer quantity = map.get(stuff.getPicker());
if(quantity!=null){
map.put(stuff.getPicker(), quantity);
}
}
Integer quantity = map.get(stuff.getPicker()); will always value quantity to null as you get it from an empty map : map = new HashMap<>(); and you populate the map only if quantity is not null :
if(quantity!=null){
map.put(stuff.getPicker(), quantity);
}
But it will never happen as the map is empty : so you never populate the map.
You have probably other issues in the code but I hope it will help you to rework your logic.

Using Hashmap contains method to check for a duplicate key

So i have an interface.
public interface ARecord {
public BigInteger getAutoID();
public String getACompId();
}
and
public class APPPRecord extends AbstratAPRecord implements ARecord{
private BigInteger autoID;
private String ACompId = null;
//setter and getter}
In service,
List<APPPRecord> PFRecord = null;
while(scroll.next()){
APPPRecord item = (APPPRecord) scroll.get(0);
List<ARecord> recs = new ArrayList<ARecord>();
recs.addAll(PFRecord);
My PFRecord list has results that are being duplicated. I have to use hash maps that can check for ACompId contains key. If the key already exists don't pass it to recs.addAll. How can I go about doing this? Any help appreciated
Update: I tried Set and still see duplicate results with HashCode() and equals() in my model class.
for(ARecord records:recs){
uniqueRecs.put(records.getACompId(), records);
Set<String> keys = uniqueRecs.keySet();
for(String key: keys){
log.debug("keys " + key);
}
}
Also tried hashMaps.
HashMap<String, ARecord > uniqueRecs = new HashMap<String, ARecord >();
for(ARecord records:recs){
if(!uniqueRecs.containsKey(records.getACompId())){
uniqueRecs.put(records.getACompId(), records);
for (String key : uniqueRecs.keySet()) {
log.debug("unique record " + key);
}
}
}
Both of them still produce duplicate results. Any ideas?
Replace List<ARecord> recs = new ArrayList<ARecord>();
with Set<ARecord> recs = new HashSet<ARecord>();
and make sure the implementations of the ARecord implements the hashcode/equals methods properly so that your set only contains distinct instances.
Make use of HashMap<K,V> class, This document will provide you with the required API.
And according to your requirement you can make use of .containsKey(Object key) method to check for the existence of the key already.
Update: I suggested this because you asked for HashMap, if duplication is the only issue you have then you can make use of .contains(Object o) method on the List you already have in-place. the interface List<> provides this method which returns a boolean value based on the presence of the value.

Get key from HashMap in Android by position or index

I have:
public static HashMap<String, String> CHILD_NAME_DOB = new HashMap<>();
Suppose the values in CHILD_NAME_DOB are:
<adam,15121990>
<roy,01051995>
<neha,05091992>
<alisha,11051992>
I am trying to fetch the last key element from CHILD_NAME_DOB. That is, I want to fetch key alisha from the example above to temporary String name.
Also I want to know on how to fetch data by index.
Eg.: if int index = 2 , I want key "Neha" in String name
TIA.
Edit: DateOfBirth value (value data in CHILD_NAME_DOB) is dynamic and is unknown. So THIS LINK is not what I want.
Single line solution:
First note that the Java HashMap does not guarantee the order of entries. So each time you iterate over a HashMap, entries appear in different positions. You will need LinkedHashMap that guarantees the predictable iteration order.
Map<String, String> CHILD_NAME_DOB = new LinkedHashMap<>();
Get the key by index:
key = (new ArrayList<>(CHILD_NAME_DOB.keySet())).get(index)
Get the value by index:
CHILD_NAME_DOB.get(key)
Thanks to #Pentium10 for this answer.
And I little modified it according to my need.
String key="default";
Iterator myVeryOwnIterator = CHILD_NAME_DOB.keySet().iterator();
while(myVeryOwnIterator.hasNext()) {
key=(String)myVeryOwnIterator.next();
//String value=(String)meMap.get(key);
}
Toast.makeText(viewEnterChildExp.getContext(), "Key: "+key , Toast.LENGTH_LONG).show();
I'm getting the last key element by this.
I'll update as soon I also get to find an easy way to key by index.
This way to get key....
public static String getHashMapKeyFromIndex(HashMap hashMap, int index){
String key = null;
HashMap <String,Object> hs = hashMap;
int pos=0;
for(Map.Entry<String, Object> entry : hs.entrySet())
{
if(index==pos){
key=entry.getKey();
}
pos++;
}
return key;
}
You can also use an ArrayMap instead of a HashMap. To get the value by index use:
ArrayMap.valueAt(index);
To get the Key at an index use:
ArrayMap.keyAt(index);
Fetching the "last" key and fetch by index is not supported by HashMap. You can use a LinkedHashMap and lookup the element with index 2 (or the last element) by iterating over it. But this will be a O(n) operation.
I suggest you use a List<Pair<String, String>> if the order of the keys/values is important to you and you wish to do index based lookup.
If both key based and index based lookup is important to you, you could use a combined data structure that consists of both a List and a HashMap, but note that removal of elements will be O(n).
You can create a class Child
public class Child(){
private String name;
private String number;
....
}
and then put this object in a List
public static List<Child> CHILD_NAME_DOB = new ArrayList<Child>(); // using LinkedList would defeat the purpose
in this way you can invoke the method get(int index), that returns the element at the specified position in this list.
In your example
<adam,15121990>
<roy,01051995>
<neha,05091992>
<alisha,11051992>
invoking CHILD_NAME_DOB.get(2) you'll get <neha,05091992>(as Child object)
HashMap does not have a concept of ordering, so getting the n-th entry does not make sense. You could use a TreeMap instead, which is ordered on its keys.
However, you should reconsider your model as you seem to have conflicting interests. On the one hand, accessing by index is typical for Lists, whereas accessing by key is typical for Maps. I'm not sure in which situation you'd want to do both.
If you really want to do both index and key accessing, you could write your own data structure that stores the data in a list combined with a mapping from key to index and vice versa. I would recommend against this, but if that's really what you want, then I think that's the best solution.
I know it is not the best solution, but what about this solution (pseudocode!). Just combine List and Map in one class.
public class UserBirthday {
private List<String> names = new ArrayList<>();
private Map<String, String> CHILD_NAME_DOB = new HashMap<String, String>();
public void add(String name, String bd) {
if (!CHILD_NAME_DOB.containsKey(name)) {
names.add(name);
}
CHILD_NAME_DOB.put(name, bd);
}
public String getByName(String name) {
return CHILD_NAME_DOB.get(name);
}
public String getByIndex(int index) {
return getByName(names.get(index)); // TODO: range test
}
public static void main(String[] args) {
UserBirthday ub = new UserBirthday();
ub.add("dit", "12345678");
ub.add("lea", "234239423");
ub.add("alex", "43534534");
ub.add("ted", "099098790");
System.out.println(ub.getByIndex(2));
System.out.println(ub.getByName("alex"));
}
}
You may get some problems if you remove an entry, but it should be just a suggestion.
for (String key : hmList.keySet()) {
String value = hmList.get(key);
Log.e("HashMap values", "key=" + key + " ,value=" + value);
}

How to edit Hibernate Search java Source Code, or maybe a workaround?

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));
}
}

Searching a HashMap<String, Arraylist<Users>> or HashMap<String, HashSet<Users>>

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

Categories