对于由属性文件控制的循环迭代?

For Loop iterations controlled by properties file?

我有一个包含 method 的应用程序,该应用程序用于使用 For-Loop:

循环遍历 Hash Map
public void iterateHashMap(Map<Dog, List<String>> mapOfDogsAndDescriptions){

        for (Map.Entry<Dog, List<String>> entry : mapOfDogIdsAndStrings.entrySet()) {
            String key = entry.getKey().getId();
            List<String> StringList = entry.getValue();

            //do something
            }

    }

我希望能够根据我的 properties 文件中的 属性 定义循环迭代 的次数

例如如果 属性 设置为 3,则它只会遍历 Hash Map.

中的前 3 个键

这是我第一次在 Java 应用程序中使用 properties file,我该怎么做?

你在使用任何框架吗?在 Spring 框架中,您可以这样做:

@Resource(name = "properties")
private Properties properties;

并且在您的 applicationContext 中:

<bean id="properties"
      class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="location" value="classpath:urls.properties"></property>
</bean>

最后,在你的方法中:

int counter = 0;

Integer limit = Integer.parseInt(properties.getProperty("some property"));

for(//Some conditions){
    //Some code

    counter++;
    if(counter > limit) break;
}

我会这样做:

public void iterateHashMap(Map<Dog, List<String>> mapOfDogsAndDescriptions){
    int count = Integer.parseInt(System.getProperty("count"));
    for (Map.Entry<Dog, List<String>> entry : mapOfDogIdsAndStrings.entrySet()) {
        if (count-- <= 0)
            break;
        String key = entry.getKey().getId();
        List<String> StringList = entry.getValue();

        //do something
    }

}

纯 java 你可以做到

Properties prop = new Properties();
String propFileName = "config.properties";

InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);

if (inputStream != null) {
    prop.load(inputStream);
} else {
    throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
}

int cpt  = Integer.valueOf(prop.getProperty("counter"));
int cptLoop = 0;
for (Map.Entry<Dog, List<String>> entry : mapOfDogIdsAndStrings.entrySet()) {
    if (cptLoop == cpt)
        break;
    String key = entry.getKey().getId();
    List<String> StringList = entry.getValue();

    //do something
    cptLoop++;
}