0

I am trying to swap the max and the min using Collections.swap but it is not working when the max or the min is twice or more in the ArrayList

Sandeepa
  • 3,457
  • 5
  • 25
  • 41
beginCS
  • 13
  • 3
  • 3
    Without code we stand only a microscopic chance of helping you out here. When you [create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve), I am sure we can and will help. You will also need to specify the expected outcome clearly. – Ole V.V. Jan 26 '19 at 06:52
  • Post your code so people can see what you have actually tried. – Leo Aso Jan 26 '19 at 06:53
  • 1
    `yourArrayList.indexOf(Collections.max(yourArrayList))`? `indexOf`“Returns the index of the first occurrence of the specified element in this list”. – Ole V.V. Jan 26 '19 at 06:56

2 Answers2

0

Assuming your ArrayList is sorted, you can deduplicate it pretty easily (see How to efficiently remove duplicates from an array without using Set). Once it is definitely duplicated, you will no longer have the same problem that you are encountering.

If you are not sorting the ArraList, you can simply call the sort method with a comparator (see javadoc https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html).

TCCV
  • 3,142
  • 4
  • 25
  • 30
0
int maxValue = Collections.max(list);  //Get the max value of your ArrayList
int maxIndex = list.indexOf(maxValue); //Get the first index of maxValue
int minValue = Collections.min(list);  //Get the min value of your ArrayList
int minIndex = list.indexOf(minValue);  //Get the first index of minValue
Collections.swap(list, maxIndex, minIndex);  //swapping 

I think this is actually what you want. Here list.indexOf(maxValue) returns the first index of maxValue from your ArrayList, though multiple maxValue present in your ArrayList. And similarly list.indexOf(minValue) return the same for minValue.

S.Mandal
  • 172
  • 1
  • 10