有什么方法可以使超出lambda范围的字计数器吗?

时间:2019-04-03 14:52:26

标签: java parsing

我需要为lambda函数范围之外的每个“如果条件”创建一个单词计数器。我只需要计算特定单词出现的频率即可。我怎样才能做到这一点?我需要编写另一个函数而不是lambda函数吗?你们觉得呢?

private void readJSON(){
    String jsonFilePath = "animals.json";



    try(FileReader fileReader = new FileReader(jsonFilePath)){
        JsonObject json = (JsonObject) Jsoner.deserialize(fileReader);

        JsonArray animals = (JsonArray) json.get("animals");

        System.out.println("\nAnimals are :");
        animals.forEach(animal -> {
            JsonObject animalObject = (JsonObject) animal;

           int i=0;
           if (animalObject.get("typeof").equals("herbivore")){
               i++;
           }
           System.out.println("The amount of herbivores is: " + i);

            int j=0;
            if (animalObject.get("typeof").equals("herbivore") || animalObject.get("typeof").equals("carnivorous") && animalObject.get("growth").equals("small")){
                j++;
            }
            System.out.println("The amount of small herbivores or carnivorous is: " + j);

            int k=0;
            if (animalObject.get("typeof").equals("omnivorous") && !animalObject.get("growth").equals("high")){
                k++;
            }
            System.out.println("The amount of not high omnivorous is: " + k);

            System.out.println("Weight : " + animalObject.getString("weight")+", Growth : " + animalObject.get("growth")+", Type of : " + animalObject.get("typeof"));
        });

    } catch (Exception ex){
        ex.printStackTrace();
    }
}

2 个答案:

答案 0 :(得分:0)

只需在forEach之外声明i,j和k。因此它们将在lambda调用中“共享”。

答案 1 :(得分:0)

您可以创建一个保存计数的类和一个保存值及其计数的映射。这是即时代码,如有需要,请对其进行调整:

  class TypeCounter {
    private final AtomicInteger cnt = new AtomicInteger();
    private final String name;

    TypeCounter(String name) {
      this.name = name;
    }

    public void inc() {
      cnt.incrementAndGet();
    }

    @Override
    public String toString() {
      StringBuilder builder = new StringBuilder();
      builder.append("TypeCounter [result=");
      builder.append(cnt.get());
      builder.append(", ");
      if (name != null) {
        builder.append("name=");
        builder.append(name);
      }
      builder.append("]");
      return builder.toString();
    }
  }

public Console() {
    String names = "aa,aa,bb,aa,cc,ee,ee,ee";
    List<String> nameList = Arrays.asList(names.split(","));
    final Map<String, TypeCounter> test = new HashMap<>();
    nameList.forEach(item -> {
      TypeCounter cnt = test.get(item);
      if (Objects.isNull(cnt)) {
        TypeCounter tc = new TypeCounter(item);
        tc.inc();
        test.put(item, tc);
      } else {
        cnt.inc();
      }
    });

    System.out.println(test);
  }

  public static void main(String[] args) throws Exception {
    new Console();
  }