Getting Max Value from an Arraylist of Objects

Getting max value from an arraylist of objects?

Use a Comparator with Collections.max() to let it know which is greater in comparison.


Also See

  • How to use custom Comparator

How to find the max element from an array list of objects?

As your ArrayList contains Forecast objects you'll need to define how the max method should find the maximum element within your ArrayList.

something along the lines of this should work:

ArrayList<Forecast> forecasts = new ArrayList<>();
// Forecast object which has highest temperature
Forecast element = Collections.max(forecasts, Comparator.comparingInt(Forecast::getTemperature));
// retrieve the maximum temperature
int maxTemperature = element.getTemperature();

Getting max value from an arraylist of objects

About your Methode getTotalPop()

  1. c should be a long variable and in initialized to 0 because now you are trying to increment a string which is impossible.
  2. you are iterating about a list of cities so iter.next() will give you a city but you want the population of this city so call c += iter.next().getPop();
  3. You don't have to use an iterator. It is okay but you won't get a benefit in this case. My recommendation use a enhanced for/foreach loop.

So use this(iterator):

public long getTotalPop(){
long result = 0;
Iterator<City> iter = cities.iterator();

while(iter.hasNext()){
result += iter.next().getPop();
}
return result;
}

or this(enhanced for/foreach loop):

public long getTotalPop(){
long result = 0;

for (City city : cities) {
result += city.getPop();
}
return result;
}

About your Methode getLargest()

There are some ways to do the job you could use an variable largest pop initialized to 0 and compare each City population with this variable and set it to the pop if it is greater. Or set your pop of the first City as the value to be compared.

With first City:

public City getLargest() {
if (!cities.isEmpty()) {
City largest = cities.get(0);
for (int i = 1; i < cities.size(); i++) {
City city = cities.get(i);
if (largest.getPop() < city.getPop()) {
largest = city;
}
}
return largest;
}
return null;
}

Furthermore because you don't initialize cities in the construtor other than to the new ArrayList don't do that in the constructor but like this:

private List<City> cities = new ArrayList<>();

public Country(String name, City capital, int pop) {
this.name = name;
this.capital = capital;
this.pop = pop;
this.cities.add(capital);
}

At last why is the pop of the country not the same as the pop of all of the cities it has? It would make totaly sense to initialize pop to the result of getTotalPop()

Grouping arraylist of objects and getting max value per group in java

In case you have to sort something, List is not a perfect match of the collection. Depending on results, you have to choose best collection.

In your example, I do not see how you want to use List<Result> tempResultList. It seems, that you use is only as temporary collection to get you main objective - get top resulst of all participant. But I can see following things:

First: You already have a List<Result> tempResultList with sorted results (top results at the beginning). All you need is just iterate over this list and for each participant get the first result:

Map<Integer, Result> topResults =  new LinkedHashMap<>();

for(Result result : tempResultList) {
if(!topResults.containsKey(result.getParticipant().getId()))
topResults.put(result.getParticipant().getId(), result);
}

Notes: hree I got throug your tempResultList and fill a map, where key is a participant's id and a value - participant's result. If paraticipant is not in a map, then add his result to it (first one in the sorted list will be the top result). You can use here LinkedHashMap to sort keys in map according it apperas in the tempResultList, or TreeMap - to sort it by participant's id. Or even - 'HashMap', when you do not care about an order of topResults.values().

Second: You can build tempResultList and then sort the top rated results at the same time, using Map<Integer, Set<Result>> res. You already has a comparator you need Result.ResultComparatorMeasurement. Key of the map - is a participant's id, value - sorted list of participant's results, with top results first.

public List<Result> listResultsForCompetition(String competitionName) {
Map<Integer, Set<Result>> participantResults = new HashMap<>();

for (Result result : resultList) {
int participantId = result.getParticipant().getId();

if (!participantResults.containsKey(participantId))

// TreeSet will sort results according to given comparator (top results first)
participantResults.put(participantId, new TreeSet<>(Result.ResultComparatorMeasurement));

        participantResults.get(participantId).add(result);
}

Map<Integer, Result> topParticipantResults = new HashMap<>();

for (Map.Entry<Integer, Set<Result>> entry : participantResults.entrySet())
topParticipantResults.put(entry.getKey(), entry.getValue().iterator().next());

List<Result> topResults = new ArrayList<>(topParticipantResults.values());

return topResults;
}

Notes: I do not use stream API here to make it maximum clear. I use TreeSet<Result>(comparator) to receive a sorted set of results (ATTENTION!!! - Set use comparator to fined and exclude duplication, so your comparator should not only compare results, but work correctly where two instance of Result have same measurement). Map<Integer, Set<Result>> participantResults contains all results grouped by participant's id.

There are other way to solve this task. I gave you only 2 ideas how to do it.

How to find second highest number in ArrayList of Objects value

public float secondHighest(ArrayList<Float> array){
float highest = 0;
for(float i : array){
if(i > highest) highest = i;
}
float secondHighest = 0;
for(float i : array){
if(i > secondHighest && i < highest) secondHighest = i;
}
return secondHighest;
}

Getting min/max float value of an ArrayList of Object

Assuming you have an array list of people...

    Collection<Person> people = new ArrayList<>();

This is how you get the max and min value people

    Person maxValuePerson = people.parallelStream()
.max(Comparator.comparing(p -> ((Person) p).getMyValue()))
.get();
Person minValuePerson = people.parallelStream()
.min(Comparator.comparing(p -> ((Person) p).getMyValue()))
.get();

You can then group the people by Month by using a Map<People> and a Calendar instance as follows:

    HashMap<Integer,ArrayList<Person>> monthMap = new HashMap<>();

Calendar cal = Calendar.getInstance(); //expensive operation... use sparingly

for (Person p : people){
cal.setTime(p.getDate()); //Sets this Calendar's time with the person's Date.
int month = cal.get(Calendar.MONTH); //gets int representing the month
ArrayList<Person> monthList = monthMap.get(month);

//initialize list if it's null (not already initialized)
if(monthList == null) {
monthList = new ArrayList<>();
}

monthList.add(p); //add the person to the list

// put this month's people list into the map only if it wasn't there to begin with
monthMap.putIfAbsent(month, monthList);
}

Putting it all together, here's a full working example that you can test:

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;

public class MinMaxTest {

public static void main(String[] args) {

Random rand = new Random();

//Assuming an array list of people...
Collection<Person> people = new ArrayList<>();

for (int i = 0; i < 50; i++){
Person p = new Person();
p.setMyvalue(rand.nextFloat());
p.setDate(new Date(rand.nextLong()));
people.add(p);
}

//This is how you get the max and min value people
Person maxValuePerson = people.parallelStream()
.max(Comparator.comparing(p -> ((Person) p).getMyValue()))
.get();
Person minValuePerson = people.parallelStream()
.min(Comparator.comparing(p -> ((Person) p).getMyValue()))
.get();

//to group the people by month do the following:
HashMap<Integer,ArrayList<Person>> monthMap = new HashMap<>();

Calendar cal = Calendar.getInstance();

for (Person p : people){
cal.setTime(p.getDate());
int month = cal.get(Calendar.MONTH);
ArrayList<Person> monthList = monthMap.get(month);
if(monthList == null)
monthList = new ArrayList<>();
monthList.add(p);
monthMap.putIfAbsent(month, monthList);
}

for(Integer i : monthMap.keySet()){
System.out.println("Month: "+ i);
for(Person p : monthMap.get(i)){
System.out.println(p);
}
}

}

static class Person implements Serializable {
private float myvalue;
private Date date;

public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public float getMyValue() {
return myvalue;
}
public void setMyvalue(float myvalue) {
this.myvalue = myvalue;
}
}

}

How to get maximum value from the Collection (for example ArrayList)?

You can use the Collections API to achieve what you want easily - read efficiently - enough
Javadoc for Collections.max

Collections.max(arrayList);

Returns the maximum element of the given collection, according to the natural ordering of its elements. All elements in the collection must implement the Comparable interface.

Finding max or min element of arraylist objects

You can do it by using some data structures to store the minima and maxima, for example. This example adds a method to your Main that outputs both the minima and the maxima of the version numbers.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {

public static void main(String[] args) {

List<Ex> list = new ArrayList<Ex>();

Ex rec1 = new Ex("HR3-A1234", 0.00);
Ex rec2 = new Ex("HR3-A1234", 0.01);
Ex rec3 = new Ex("HR3-A1234", 1.00);
Ex rec4 = new Ex("HR3-A2345", 0.00);
Ex rec5 = new Ex("HR3-A2345", 0.01);
Ex rec6 = new Ex("HR3-A3456", 0.01);
Ex rec7 = new Ex("HR3-A3456", 1.00);
Ex rec8 = new Ex("HR3-A4567", 0.01);

list.add(rec1);
list.add(rec2);
list.add(rec3);
list.add(rec4);
list.add(rec5);
list.add(rec6);
list.add(rec7);
list.add(rec8);

displayMinMaxOfEach(list);
}

public static void displayMinMaxOfEach(List<Ex> exes) {
// declare two maps for storing minumum and maximum values
Map<String, Double> minExes = new HashMap<String, Double>();
Map<String, Double> maxExes = new HashMap<String, Double>();

// check each Ex in the list in order to get the minimum values
exes.forEach((Ex ex) -> {
if (minExes.containsKey(ex.getId())) {
// if already contained, check if the new version is lower
if (minExes.get(ex.getId()) > ex.getVersion()) {
// if it is lower, overwrite the old version number
minExes.put(ex.getId(), ex.getVersion());
}
} else {
// if not already contained, just add it to the map
minExes.put(ex.getId(), ex.getVersion());
}
});

// check each Ex in the list in order to get the maximum values
exes.forEach((Ex ex) -> {
if (maxExes.containsKey(ex.getId())) {
// if already contained, check if the new version is higher
if (maxExes.get(ex.getId()) < ex.getVersion()) {
maxExes.put(ex.getId(), ex.getVersion());
}
} else {
// if not already contained, just add it to the map
maxExes.put(ex.getId(), ex.getVersion());
}
});

// print minumum values from the minimum map
System.out.println("Minimum versions:");
minExes.forEach((id, version) -> {
System.out.println(id + ": " + version);
});

// print maximum values from the maximum map
System.out.println("Maximum versions:");
maxExes.forEach((id, version) -> {
System.out.println(id + ": " + version);
});
}
}


Related Topics



Leave a reply



Submit