Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

VasilKos avatar VasilKos 17 Точки

Followers Fundamentals Java

Може ли малко помощ за принтирането накрая.

Followers - Pastebin.com

Първият вход излиза, проблемът е при втория.

followers.entrySet().stream().sorted((e1, e2) -> Integer.compare(e2.getValue().size(), e1.getValue().size()))
        .forEach(entry -> {
            System.out.printf("%s: %d%n", entry.getKey(), entry.getValue().get(0)+entry.getValue().get(1));
        });

Условието на задачата: 

Followers

Now that Pesho has successfully created an account, he wants to connect with other users and gain as many followers, likes and comments as possible.

Create a program that keeps information about Pesho's followerslikes and comments. Keep a record of the followers, each with the likes and comments Pesho has received from them.

You will be receiving lines with commands until you receive the "Log out" command.  There are four possible commands:

  • "New follower: {username}":
    • Add the username, to your records (with 0 likes and 0 comments). If person with the given username already exists ignore the line.
  • "Like: {username}: {count}":
    • If the username doesn't exist, add it to your records with the given count of likes.
    • If the username existincrease the count of likes with the given count.
  • "Comment: {username}":
    • If the username doesn't exist, add it to your records with 1 comment.
    • If the username existsincrease the count of commens with 1.
  • "Blocked: {username}":
    • Delete all records of the given username. If it doesn’t exist, print:

 "{Username} doesn't exist."

 

In the end, you have to print the count of followers, each follower with his/her likes and comments (the sum of likes and comments) sorted in descending order by the likes and then by their username in ascending order in the following format: 

{count} followers

{username}: {likes+comments}

{username}: {likes+comments}

...

Input

  • You will be receiving lines until you receive the "Log out" command.
  • The input will always be valid.

Output

  • Print the users with their likes in the format described above.

Examples

Input

Output

New follower: gosho

Like: gosho: 5

Comment: gosho

New follower: gosho

New follower: tosho

Comment: gosho

Comment: tosho

Comment: pesho

Log out

3 followers

gosho: 7

pesho: 1

tosho: 1

Input

Output

Like: A: 3

Comment: A

New follower: B

Blocked: A

Comment: B

Like: C: 5

Like: D: 5

Log out

3 followers

C: 5

D: 5

B: 1

Тагове:
0
Fundamentals Module
MartinBG avatar MartinBG 4803 Точки

Сортирането трябва да е по броя лайкове, а не по размера на List-a:

.sorted((e1, e2) -> Integer.compare(e2.getValue().size(), e1.getValue().size())) // wrong

.sorted((e1, e2) -> Integer.compare(e2.getValue().get(0), e1.getValue().get(0))) // correct

 

Алтернативно, ако не пазим данните в TreeMap, а в HashMap, може да сортираме така:

.sorted(Map.Entry
        .<String, List<Integer>>comparingByValue(Comparator.comparingInt(l -> l.get(0)))
        .reversed()
        .thenComparing(Map.Entry.comparingByKey()))

 

0
VasilKos avatar VasilKos 17 Точки

Благодаря. 

Надявам се с времето да се свиква с тези сортировки, но на този етап са доста трудни, а реално дават крайния резултат.

1
tomusa avatar tomusa -3 Точки

The information you shared is very accurate, it gives me the knowledge wordle that I need to learn. Thank you for sharing this useful information.

-1
bekean avatar bekean -2 Точки

The author's well-structured Pokedoku arguments make it easy for readers to follow the logical flow of the content.

0
victorpatrick avatar victorpatrick 7 Точки

Според условието на задачата, трябва да принтирате информацията за всички последователи на Пешо, сортирани по брой харесвания (likes) в намаляващ ред и след това по име във възходящ ред. При принтирането трябва да изведете сумата от харесванията и коментарите за всеки потребител.

Проблемът ви произлиза от изваждането на елементите entry.getValue().get(0) и entry.getValue().get(1). Това се дължи на факта, че методът getValue() връща ви колекция от стойности, а не отделни стойности. За да получите сумата на харесванията и коментарите, можете да използвате методите sum() и size() върху колекцията:

followers.entrySet().stream()
        .sorted((e1, e2) -> Integer.compare(
                e2.getValue().stream().mapToInt(Integer::intValue).sum(),
                e1.getValue().stream().mapToInt(Integer::intValue).sum()))
        .forEach(entry -> {
            int likesAndCommentsSum = entry.getValue().stream().mapToInt(Integer::intValue).sum();
            System.out.printf("%s: %d%n", entry.getKey(), likesAndCommentsSum);
        });
Това ще сортира последователите по сумата от харесванията и коментарите им в намаляващ ред и ще принтира информацията в желания формат.

Моля, обърнете внимание, че този код предполага, че стойностите на харесванията и коментарите са цели числа. Ако те са представени като низове, може да е необходимо да ги преобразувате в целочислени стойности преди да ги сумирате.
Надявам се, че това ще ви помогне да решите проблема си. tunnel rush

-1
sneezefreeze avatar sneezefreeze 4 Точки

Javarevisited is another great free games to check out. All the fundamentals of programming are covered in depth, as well as frameworks, design patterns, APIs, architectural styles, multithreading, OOPS principles, a plethora of tutorials, casting in Java, connections to books, interview questions, and much more.

0
karausa avatar karausa 3 Точки

Оценявам информацията, която споделяте. Наистина съм впечатлен от вашето количество много точна и полезна информация за Java. slope

0
mira23a avatar mira23a 2 Точки

It is also one of the most often used languages in the media. So, if you want to improve your Java knowledge and stay up to date on the latest Java developments, dino game we've limited down your selections to the greatest resources available on the Internet. 

0
18/09/2023 05:33:20
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.