0

I have an arraylist, aliens, of the following objects:

  public class Alien{
    public int[] pos;
    public int speed;
    
    public Alien(int[] pos, int speed) {
      this.pos = pos;
      this.speed = speed;
    }
    @Override
    public String toString() {
      return "(" + this.speed + ")[" + this.pos[0] + "," + this.pos[1] + "]";
    }
  }

and I've gotten this far with what I'm looking for, assuming I'm going in the right direction:

aliens.stream()
      .filter(x -> x.pos[1] == SpaceInvaders.ship)
      .collect(Collectors.groupingBy(x -> x.pos[0]));

where SpaceInvaders.ship is an int representing the column that I'm looking to intersect on. If you print this out, it shows {0=[(2)[0,4], (-3)[0,4]], 1=[(-7)[1,4]]}, indicating that they are correctly grouped by the first element of their position. As you can see, the positions aren't necessarily unique, so I need to do some processing on a group to determine other criterion, but I need to only process the group with the highest value key. If I use maxBy the way that most of the online documentation describes, I get the max for each group, but I need only the max of the groups by the key representing the row the alien is on.

I'm stuck at this point. How does one do a maxBy on the keys of the return value of a collect(groupingBy())?

Naman
  • 27,789
  • 26
  • 218
  • 353
Ryan Wood
  • 352
  • 2
  • 10
  • 1
    There’s no need for grouping at all. `OptionalInt max = aliens.stream() .filter(x -> x.pos[1] == SpaceInvaders.ship) .mapToInt(x -> x.pos[0]) .max(); if(max.isPresent()) { int maxKey = max.getAsInt(); List matches = aliens.stream() .filter(x -> x.pos[1] == SpaceInvaders.ship && x.pos[0] == maxKey) .collect(Collectors.toList()); }` See also [How to force max to return ALL maximum values in a Java Stream?](https://stackoverflow.com/a/29339106/2711488). It’s iterating twice, but in most cases still more efficient than grouping. – Holger Jan 29 '21 at 19:51

1 Answers1

1

There are several ways to get a map entry by max key:

  1. Use sorted map like TreeMap and then get use lastEntry method:
TreeMap<Integer, List<Alien>> map =  aliens.stream()
        .filter(x -> x.pos[1] == SpaceInvaders.ship)
        .collect(Collectors.groupingBy(
            x -> x.pos[0], TreeMap::new, Collectors.toList()
        ));
System.out.println(map.lastEntry());
  1. (by Holger's comment) Use Stream::max returning Optional result
aliens.stream()
        .filter(x -> x.pos[1] == SpaceInvaders.ship)
        .collect(Collectors.groupingBy(x -> x.pos[0])) // non-sorted map
        .entrySet()
        .stream()
        .max(Map.Entry.comparingByKey()) // returns Optional<Map.Entry>
        .ifPresent(System.out::println); // print entry with max key if available
  1. Sort entries of the aliens by key in reverse order and pick up only one entry:
aliens.stream()
        .filter(x -> x.pos[1] == SpaceInvaders.ship)
        .collect(Collectors.groupingBy(x -> x.pos[0])) // non-sorted map
        .entrySet()
        .stream()
        .sorted(Map.Entry.<Integer, List<Alien>>comparingByKey().reversed())
        .limit(1)
        .forEach(System.out::println);
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
  • This is the information I was missing for sure. I was having trouble figuring out the type of the return, and when I found it was a map, I was able to move forward from there. The `entrySet()` to get it back into a stream, and then `comparingByKey()` are much cleaner than what I arrived at independently. Love it! – Ryan Wood Jan 28 '21 at 21:21
  • 2
    `sorted(comparator.reversed()).limit(1)`? Why not `max(comparator)`? – Holger Jan 29 '21 at 19:42
  • @Holger, you're right, this option just fell through the cracks – Nowhere Man Jan 29 '21 at 20:34