Home > Enterprise >  How to print keys of specific values in HashMap?
How to print keys of specific values in HashMap?

Time:12-03

The question is how to pritn the books that have value = 1 in the HashMap, using the printWhiteRavens(ArrayList<String> whiteRavens) method ? In the code ive deleted the array with the books so the code could be shorter.

 public static HashMap<String, Integer> createBooksCounter() {
        HashMap<String,Integer> createBooksCounter = new HashMap<>();
        createBooksCounter.put("Chicken Abroad",5);
        createBooksCounter.put("Lord With Sins",3);
        createBooksCounter.put("Fish And Horses",4);
        createBooksCounter.put("Mistress Of Devotion",2);
        createBooksCounter.put("Guardians And Gangsters",3);
        createBooksCounter.put("Bandit Of The Void",1);
        createBooksCounter.put("Lions Of Dread",1);
        createBooksCounter.put("Future Of Fire",2);
        createBooksCounter.put("Driving Into The Depths",1);
        createBooksCounter.put("Starting The Demons",1);
        createBooksCounter.put("Maid With Blue Eyes",2);
        createBooksCounter.put("Lovers In The Forest",1);
        createBooksCounter.put("Destruction Of The Faceless Ones",1);

        return null;
    }

    public static void countBook(HashMap<String, Integer> booksCounter, String book) {

    }

    public static ArrayList<String> findWhiteRavens(HashMap<String, Integer> booksCounter) {
        return null;    
    }

    public static void printWhiteRavens(ArrayList<String> whiteRavens) {
        return null;
    }

    public static void main(String[] args) {
    }

CodePudding user response:

Using Stream :

yourMap.entrySet().stream().filter(e -> e.getValue() == 1)
                .forEach(element -> System.out.println(element.getKey()));

CodePudding user response:

Filter all entries of the map, create a list from the map's keys, these are your book titles. Pass that list to printWhiteRavens which then prints the titles:

public static void main(String[] args) {
  Map<String,Integer> map = createBooksCounter();
  List<String> list = map.entrySet().stream().
                         filter(e->e.getValue()==1).
                         map(e->e.getKey()).
                         collect(Collectors.toList());
  printWhiteRavens(list);
}

public static void printWhiteRavens(List<String> whiteRavens) {
  whiteRavens.stream().forEach(System.out::println);
}

Also you have to edit your createBooksCounter method to return the map using

return createBooksCounter;

CodePudding user response:

Your method createBooksCounter should probably return the map instead of null. Note that usually you declare members as the highest common interface offering the contract you need. So even though you might instantiate HashMap, you declare the field as a Map. The same holds for method parameters and return types. Regarding the name, I would name it bookCounts, since the map is not counting anything, just representing books and their 'counts'.

public static Map<String, Integer> createBookCounts() {
    Map<String, Integer> bookCounts = new HashMap<>();
    bookCounts .put("Chicken Abroad",5);
    // ...
    return bookCounts;
}

The method findWhiteRavens needs to look up all books in the map which have count==1. This is contrary to the normal usage of a Map, where you look things up by their key rather than their value. I suggest either to use a map where count is the key, and the values are lists of books (having that count) OR to use a List with Book objects with the fields title and count. The latter approach is in my opinion the simplest and most object-oriented design (using maps to collect related fields is a code smell):

class Book {

    String title;
    int count;

    Book(String title, int count) {
        this.title = title;
        this.count = count;
    }

    // accessors to be added
}

// ...

List<Book> books = new ArrayList<>();
books.add(new Book("Chicken Abroad", 5));

You could print books with count==1 in one go like this:

books.stream()
    .filter(book -> book.getCount() == 1)
    .map(book -> book.getTitle());
    forEach(book -> System.out.println(book));

If you prefer to use a map, then this would make more sense:

private static Map<Integer, List<String>> bookTitlesByCount = new HashMap<>();

public static void main(String[] args) {
    addBookTitle("Chicken Abroad", 5);
    List<String> whiteRavens = bookTitlesByCount.get(1);
    // print them
}

private static void addBookTitle(String title, int count) {
    List<String> bookTitles = bookTitlesByCount.get(count);
    if (bookTitles == null) {
        bookTitles = new ArrayList<>();
        bookTitlesByCount.put(count, bookTitles);
    }
    bookTitles.add(title);
}
  • Related