Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Comparator;
- import java.util.Map;
- import java.util.TreeMap;
- public class Alex {
- public static void main(String[] args) {
- Map<Integer, String> map = new TreeMap<>
- (Map.of(6, "D", 4, "F", 1, "E", 3, "B", 2, "C", 5, "A"));
- map.entrySet().stream()
- .sorted(Map.Entry.comparingByKey())// <- Сортиране по ключ във възходящ ред
- .forEach(a -> System.out.printf("%d : %s%n", a.getKey(), a.getValue()));
- System.out.println("-----");
- map.entrySet().stream()
- .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))// <- Сортиране по ключ в низходящ ред
- .forEach(a -> System.out.printf("%d : %s%n", a.getKey(), a.getValue()));
- System.out.println("-----");
- map.entrySet().stream()
- .sorted(Map.Entry.comparingByValue())// <- Сортиране по стойност във възходящ ред
- .forEach(a -> System.out.printf("%d : %s%n", a.getKey(), a.getValue()));
- System.out.println("-----");
- map.entrySet().stream()
- .sorted(Map.Entry.comparingByKey())// <- Сортиране по ключ във възходящ ред
- .filter(a -> a.getKey() % 2 != 0)// <- Взимаме само нечетните
- .forEach(a -> System.out.printf("%d : %s%n", a.getKey(), a.getValue()));
- }
- }
- // Конзолата отпечатва:
- //1 : E
- //2 : C
- //3 : B
- //4 : F
- //5 : A
- //6 : D
- //-----
- //6 : D
- //5 : A
- //4 : F
- //3 : B
- //2 : C
- //1 : E
- //-----
- //5 : A
- //3 : B
- //2 : C
- //6 : D
- //1 : E
- //4 : F
- //-----
- //1 : E
- //3 : B
- //5 : A
Add Comment
Please, Sign In to add comment