Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

java - How to get the max by key of the result of groupingBy

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())?

question from:https://stackoverflow.com/questions/65944241/how-to-get-the-max-by-key-of-the-result-of-groupingby

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...