Advertisement
Guest User

Untitled

a guest
Oct 20th, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. import static java.util.Comparator.comparing;
  2. import static java.util.stream.Collectors.collectingAndThen;
  3. import static java.util.stream.Collectors.groupingBy;
  4. import static java.util.stream.Collectors.maxBy;
  5. import static java.util.stream.Collectors.toList;
  6.  
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. import java.util.Optional;
  10.  
  11. public class GroupByGetMaxToListSort {
  12.  
  13. private static List<Obj> raw() {
  14. final List<Obj> raw = new ArrayList<>();
  15. raw.add(new Obj("a", 6));
  16. raw.add(new Obj("a", 4));
  17. raw.add(new Obj("b", 8));
  18. raw.add(new Obj("c", 1));
  19. raw.add(new Obj("c", 11));
  20. raw.add(new Obj("b", 3));
  21. raw.add(new Obj("a", 7));
  22. raw.add(new Obj("c", 5));
  23. raw.add(new Obj("d", 0));
  24. return raw;
  25. }
  26.  
  27. public static void main(String[] args) {
  28. final List<Obj> result = raw().stream()
  29. .collect(groupingBy(Obj::getType, collectingAndThen(maxBy(comparing(Obj::getVal)), Optional::get)))
  30. .values().stream().sorted(comparing(Obj::getVal)).collect(toList());
  31. System.out.println(result);
  32. // output is [{"type":"d", val":"0}, {"type":"a", val":"7}, {"type":"b", val":"8}, {"type":"c", val":"11}]
  33. }
  34.  
  35. }
  36.  
  37. class Obj {
  38. private String type;
  39. private int val;
  40.  
  41. public Obj(String type, int val) {
  42. this.type = type;
  43. this.val = val;
  44. }
  45.  
  46. public String getType() {
  47. return type;
  48. }
  49.  
  50. public void setType(String type) {
  51. this.type = type;
  52. }
  53.  
  54. public int getVal() {
  55. return val;
  56. }
  57.  
  58. public void setVal(int val) {
  59. this.val = val;
  60. }
  61.  
  62. @Override
  63. public String toString() {
  64. return String.format("{\"type\":\"%s\", val\":\"%s}", type, val);
  65. }
  66.  
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement