roguehippo Posted January 19, 2017 Share Posted January 19, 2017 (edited) Hello I was just wondering how i would implement a filter to get the closest npc of a certain type but to make sure it is not ~2 squares away from the npc so that im not crashing someone else's spot as that would look quite botty. Edited January 19, 2017 by roguehippo Quote Link to comment Share on other sites More sharing options...
Alek Posted January 19, 2017 Share Posted January 19, 2017 Using filters! Two ways: 1. getNpcs().filter(new Filter<NPC>() { @[member='Override'] public boolean match(NPC obj) { return obj.getPosition().distance(myPosition()) > 2; } }); 2. java.util.List<NPC> npcs = getNpcs().getAll().stream().filter(n -> n.getPosition().distance(myPosition()) > 2).collect(Collectors.toList()) Edit:Then you can use a comparator: npcs.sort(new Comparator<NPC>() { public int compare(NPC npc1, NPC npc2) { return npc1.getPosition().distance(myPosition()) - npc2.getPosition().distance(myPosition()); } }); So this will return the closest npc which is more than 2 tiles away. 2 Quote Link to comment Share on other sites More sharing options...
Explv Posted January 19, 2017 Share Posted January 19, 2017 (edited) Hello I was just wondering how i would implement a filter to get the closest npc of a certain type but to make sure it is not ~2 squares away from the npc so that im not crashing someone else's spot as that would look quite botty. Optional<NPC> npcOpt = getNpcs().getAll() .stream() .filter(n -> n.getName().equals("NPC Name") && n.getPosition().distance(myPosition()) > 2) .min((n1, n2) -> Integer.compare(n1.getPosition().distance(myPosition()), n2.getPosition().distance(myPosition()))); Explanation: Construct a Stream<NPC> of all the NPCs around the Player Filter the Stream<NPC> so that only the NPCs who's name matches "NPC Name" and is more than two tiles away from the player remain Apply the min function to the Stream<NPC> using a custom comparator that compares distances from the player (essentially returns the closest NPC to the player) Returns an Optional<NPC> With the return value of Optional<NPC>, instead of null checking you do something like: npcOpt.ifPresent(npc -> { }); For more information on the Optional class see https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html For more information on streams see http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html and https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html Edited January 19, 2017 by Explv Quote Link to comment Share on other sites More sharing options...