3

So I have these 4 variables

private final String PROG_DEPT = "PROGRAMMING/ENGINEERING";
private final String DES_DEPT = "DESIGN/WRITING";
private final String ART_DEPT = "VISUAL ARTS";
private final String SOUND_DEPT = "AUDIO";

What I want to be able to do is to get a string and compare it to the variable and then out put what the variable contains if it equals it.

For example if my string equals "ART_DEPT" then it check if there is a variable called ART_DEPT and then output "VISUAL ARTS"

I was thinking of putting it in a 2D String array or a list but I'm not really sure as to how to do what I want to do

Exikle
  • 1,155
  • 2
  • 18
  • 42

8 Answers8

8

The data type you're looking for is Map<String, String>.

Map<String, String> departmentNames = new HashMap<String, String>();
departmentNames.put("PROG_DEPT", "PROGRAMMING/ENGINEERING");
departmentNames.put("DES_DEPT", "DESIGN/WRITING");
//...etc...

//...

String dept = "PROG_DEPT";
String deptName = departmentNames.get(dept);
System.out.println(deptName); //outputs "PROGRAMMING/ENGINEERING"

A Map binds a unique key to a value. In this case both have the type String. You add bindings using put(key, value) and get the binding for a key using get(key).

Mark Peters
  • 80,126
  • 17
  • 159
  • 190
5

I would go with an enum:

package com.stackoverflow.so18327373;

public class App {
    public static void main(final String[] args) {
        final String in = "DES_DEPT";
        try {
            final Departement departement = Departement.valueOf(in);
            System.out.println(departement.getLabel());
        } catch (final IllegalArgumentException ex) {
            // in was not a known departement
            System.err.println("Bad value: " + in);
        }
    }

    public static enum Departement {
        PROG_DEPT("PROGRAMMING/ENGINEERING"), 
        DES_DEPT("DESIGN/WRITING"), 
        ART_DEPT("VISUAL ARTS"), 
        SOUND_DEPT("AUDIO");

        private final String label;

        private Departement(final String label) {
            this.label = label;
        }

        public String getLabel() {
            return this.label;
        }
    }
}

then use valueOf()

  • Wonderful answer. If the values are known at design/compile time, using enum is a very good solution. +1 – Matthias Aug 20 '13 at 05:30
4

You probably want to use some kind of Map, such as a HashMap<String,String>. I suggest you read the Javadocs for the Map interface and the HashMap class.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
3

What you need to use is a Map.

private final Map<String,String> myMap= new HashMap<String,String>() ;
{
    myMap.put("PROG_DEPT","PROGRAMMING/ENGINEERING");
    myMap.put("DES_DEPT","DESIGN/WRITING");
    myMap.put("ART_DEPT","VISUAL ARTS");
    myMap.put("SOUND_DEPT","AUDIO");
}

Then use it in the following way:

String input= "ART_DEPT" ;
System.out.println( myMap.get(input) );
Mario Rossi
  • 7,651
  • 27
  • 37
1

Sounds like you are looking for reflection (or if you want to use a different data type instead of looking up a variable in a class then a Map<String, String>). Looks like the Map approach is well covered, so only because this is interesting to me, here is the reflection approach (not that this is not the best way to solve this problem, but since you asked for checking if a variable exists and then getting it's value)

import java.lang.reflect.Field;

public class SOQuestion {
  private final String PROG_DEPT = "PROGRAMMING/ENGINEERING";
  private final String DES_DEPT = "DESIGN/WRITING";
  private final String ART_DEPT = "VISUAL ARTS";
  private final String SOUND_DEPT = "AUDIO";

  public static void main(String ... args) throws IllegalArgumentException, IllegalAccessException, InstantiationException {
    System.out.println(reflectValue("ART_DEPT", SOQuestion.class));
    System.out.println(reflectValue("COMP_DEPT", SOQuestion.class));
  }

  public static String reflectValue(String varible, Class thing) throws IllegalArgumentException, IllegalAccessException, InstantiationException {
    Field[] fs = thing.getDeclaredFields();
    for(int i = 0; i < fs.length; i++) {
      if(fs[i].getName().equals(varible)) {
        fs[i].setAccessible(true);
        return (String) fs[i].get(thing.newInstance());
      }
    }
    return null;
  }
}

The first request to print "ATR_DEPT" will print VISUAL ARTS and the second request to the nonexistent "COMP_DEPT" will return null;

Jason Sperske
  • 29,816
  • 8
  • 73
  • 124
1

Try this

      List<String> list=new ArrayList<>();
      list.add("private final String PROG_DEPT = \"PROGRAMMING/ENGINEERING\";");
      list.add("private final String DES_DEPT = \"DESIGN/WRITING\";");
      list.add("private final String ART_DEPT = \"VISUAL ARTS\";");
      list.add("private final String SOUND_DEPT = \"AUDIO\";");
      String search="ART_DEPT";
      for (String i:list){
         if(i.contains(search)){
             System.out.println(i.split("=")[1].replaceAll(";",""));
         }
      }

Live Demo here. You can do this using Map but to do that you have to create a map from these Strings.

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
1
private String getStaticFieldValue(String fieldName){
    String value = null;
    try {
        Field field = getClass().getDeclaredField(fieldName);
            if (Modifier.isStatic(field.getModifiers())){
                value = field.get(null).toString();
            }
        }
    catch (Exception e) {
        return null;
    }
    return value;
}

you have few options as mentioned above :

  1. using a Map , the disadvantage of using a map for this case is that you will have to maintain it, it means that every time you will need to add/remove/edit one of your final static fields, you will have to edit the map as well.
  2. using reflection as mentioned in this post, which is my favorite solution (the above code snippet)
Community
  • 1
  • 1
planben
  • 680
  • 6
  • 20
0

Use the concept of Map

import java.util.HashMap;
import java.util.Map;

public class MajorMap {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Map<String, String> deptMap = new HashMap<String, String>();
        deptMap.put("PROG_DEPT", "PROGRAMMING/ENGINEERING");
        deptMap.put("DES_DEPT","DESIGN/WRITING");
        deptMap.put("ART_DEPT","VISUAL ARTS");
        deptMap.put("SOUND_DEPT","AUDIO");
        System.out.println("ART_DEPT----->>"+deptMap.get("ART_DEPT")); 
    }

}
Rakesh KR
  • 6,357
  • 5
  • 40
  • 55