цикл через итератор возвращает то же значение - PullRequest
1 голос
/ 26 мая 2020
• 1000 () .next (). getName ()) всегда возвращает одну и ту же строку

Ответы [ 5 ]

1 голос
/ 26 мая 2020

Этот код отлично работает с вводом ниже:

      import java.util.*;

   public class Test {
   public static  void main(String[] ar){
    Map<String, People> entry1 = new HashMap<String , People>();
    People people1 = new People("true","name1");
    People people2 = new People("false","name2");
    People people3 = new People("true","name3");
    entry1.put("user1", people1);
    entry1.put("user2", people2);
    entry1.put("user3", people3);

    Map<String, People> entry2 = new HashMap<String , People>();
    People people4 = new People("true","name1");
    People people5 = new People("false","name2");
    People people6 = new People("true","name3");
    entry2.put("user1", people4);
    entry2.put("user2", people5);
    entry2.put("user3", people6);

    Map<String, Map<String, People>> map2 = new HashMap<String, Map<String, 
   People>>();
    map2.put("set1",entry1);
    map2.put("set2",entry2);

    Collection<People> strings = new ArrayList<>();
    strings.add(people1);
    strings.add(people6);
    strings.add(people5);
    strings.add(people3);
    strings.add(people2);

    getKeysByValue(map2, strings);

}

public static Map<String, String> getKeysByValue(Map<String, Map<String, People>> map, Collection<People> value) {

    Map<String, String> stringStringMap = new HashMap<>();

    int count = 0;
    Iterator<People> it = value.iterator();

    while (it.hasNext()) {
        People people = it.next();
        for (Map.Entry<String, Map<String, People>> entry : map.entrySet()) {
            for (Map.Entry<String, People> entry1 : entry.getValue().entrySet()) {

                String verified = people.getVerified();
                System.out.println(verified);
                System.out.println("Key : "+entry1.getKey() +" Value : "+entry1.getValue().getVerified());
                if (verified.equals(entry1.getValue().getVerified())) {
                   stringStringMap.put(entry1.getKey(), people.getName());
                }
            }
        }
    }
    System.out.println(stringStringMap);
    return stringStringMap;
   }
  }

Люди. java

  public class People {
String verified;

public  People(String verified, String name){
    this.verified = verified;
    this.name = name;
}

public String getVerified() {
    return verified;
}

public String getName() {
    return name;
}
String name;

}

1 голос
/ 26 мая 2020

Я думаю, что приведенный ниже подход будет правильным подходом к вашей проблеме:

public Map<String, String> getKeysByValue(Map<String, Map<String, Peple>> map, Collection<Peple> value) {

            Map<String, String> stringStringMap = new HashMap<>();

            int count = 0;

            Iterator<People> peopleIterator = value.iterator();

            while (peopleIterator.hasNext()) {
                for (Map.Entry<String, Map<String, Peple>> entry : map.entrySet()) {
                    for (Map.Entry<String, Peple> entry1 : entry.getValue().entrySet()) {
                        People people = peopleIterator.next();
                        String verified = people.gerVerfied();
                        if (verified.equals("true")) {
                            stringStringMap.put(entry1.getKey(), people.getName());

                        }
                    }
                }

Вам нужно сохранить итератор в переменной.

Рассмотрим простой код ниже:

Collection<String> strings = new ArrayList<>();
        strings.add("value1");
        strings.add("value2");
        strings.add("value3");
        strings.add("value4");

        while (strings.iterator.hasNext())
        {
            System.out.println(strings.iterator.next());
        }

Это будет работать бесконечно и будет печатать только значение1, но если вы измените код, как показано ниже:

Collection<String> strings = new ArrayList<>();
strings.add("value1");
            strings.add("value2");
            strings.add("value3");
            strings.add("value4");

        Iterator<String> stringIterator = strings.iterator();

        while (stringIterator.hasNext())
        {
            System.out.println(stringIterator.next());
        }

Он работает плавно.

Подробнее об итераторе можно узнать здесь : https://www.geeksforgeeks.org/how-to-use-iterator-in-java/

Кроме того, я думаю, что, поскольку вы дважды вызываете итератор, не проверяя hasNext () во втором вызове, он может выбросить java .util.NoSuchElementException

1 голос
/ 26 мая 2020

Каждый раз, когда вы вызываете value.iterator() новый объект Iterator создается с нуля, указывая на первый элемент. Чтобы этого избежать, сохраните первый результат вызова в локальной переменной.

Iterator<Peple> it = value.iterator();

while(it.hasNext()){
  // your remaiing code
}
1 голос
/ 26 мая 2020

Вы дважды вызываете next () для этого итератора. Это продвигает его вперед и подбирает имена следующих людей, которые могут не быть проверены.

Я думаю, вы просто хотите узнать имя, если это проверенный Пепл?

while (value.iterator().hasNext()) {
  for (Map.Entry<String, Map<String, Peple>> entry : map.entrySet()) {
    for (Map.Entry<String, Peple> entry1 : entry.getValue().entrySet()) {
      Peple nextPeple = value.iterator().next();
      String verified = nextPeple.gerVerfied();
      if (verified.equals("true")) { 
        stringStringMap.put(entry1.getKey(), nextPeple.getName());
      }
    }
  }
}
0 голосов
/ 26 мая 2020

Попробуйте следующее:

public Map<String, String> getKeysByValue(Map<String, Map<String, Peple>> map, Collection<Peple> value) {

    Map<String, String> stringStringMap = new HashMap<>();
    int count = 0;
    Iterator<Peple> iterator = value.iterator();
    while (iterator.hasNext()) {
        Peple p = iterator.next();
        for (Map.Entry<String, Map<String, Peple>> entry : map.entrySet()) {
            for (Map.Entry<String, Peple> entry1 : entry.getValue().entrySet()) {
                String verified = p.gerVerfied();
                if (verified.equals("true")) { 
                    stringStringMap.put(entry1.getKey(), p.getName());
                }
            }
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...