How to add two beautiful arrays so that the elements do not repeat?

ArrayList<Point> cells1 = get_move_place(x,y,fig_id); ArrayList<Point> cells2 = get_eat_figures(x,y,fig_id); 

Point is the coordinates of a point on the screen.

  • 2
    Use the Set interface - Andrey M
  • Thanks, I found this solution so far: ArrayList <Point> cells1 = get_move_place (x, y, fig_id); ArrayList <Point> cells2 = get_eat_figures (x, y, fig_id); cells1.addAll (cells2); HashSet <Point> cells3 = new HashSet (cells1); ArrayList <Point> list = new ArrayList <Point> (cells3); - Anna
  • If possible, publish the solution found in response to your question . I am sure it will help many of your colleagues in the future. - Mikhail Vaysman

2 answers 2

You can use Java 8 Stream Api to perform a distinct operation.

 ArrayList<Point> cells3 = new ArrayList<>(); cells3.addAll(cells1); cells3.addAll(cells2); List<Point> collect = cells3.stream().distinct().collect(Collectors.toList()); 
     ArrayList<Point> cells1 = get_move_place(x,y,fig_id); ArrayList<Point> cells2 = get_eat_figures(x,y,fig_id); ArrayList<Point> list = new ArrayList<Point>(cells1); for(Point x : cells2){ if (!list.contains(x)) list.add(x); } 

    such an option is a bit more readable than throwing from sheet to set and back