假設你有一個人一個數組列表...
Collection<Person> people = new ArrayList<>();
這是你如何獲得最大和最小值人
Person maxValuePerson = people.parallelStream()
.max(Comparator.comparing(p -> ((Person) p).getMyValue()))
.get();
Person minValuePerson = people.parallelStream()
.min(Comparator.comparing(p -> ((Person) p).getMyValue()))
.get();
你然後可以按月使用Map<People>
和Calendar
實例將人員按月分組,如下所示:
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);
}
全部放在一起,這裏是一個完整的工作的例子,你可以測試:
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;
}
}
}
你的對象可能需要實現'Comparable' ...只是一個想法... –
你爲什麼不去一個簡單的「for循環」?我認爲這是最直接的開始,特別是當你是初學者時。 – Matt
我不好當我複製/粘貼代碼,但它不是一個很長,但很好浮動myvalue – Helvin