2016-08-01 4 views
1

나는 float 속성을 포함하는 Person의 ArrayList를 가지고 있습니다. 내가하고 싶은 것은 Arraylist의 최소값과 최대 값을 표시하는 것입니다. Object의 ArrayList의 최소/최대 float 값 얻기

public class Person implements Serializable { 

    private float myvalue; 
    private Date date; 
    //getters setters... 

나는 Collections.min(mylist)Collections.max(mylist)을 사용하려고하지만 내가 비교를 오버라이드 (override) 할 것 같다.

내 두 번째 문제는 날짜 속성에 같은 달 (같은 해)이있는 mylist의 각 요소를 찾고 싶지만 실제로 어떻게 할 수 있는지 보지 못합니다.

누군가 나를 도울 수 있기를 바랍니다.

첫 번째 클래스가 구현 한 : (이것은 내가 추측 숙제 문제로)

+2

귀하의 목적은 아마도'Comparable' ... 그냥 생각을 구현해야 ... –

+2

왜하지 간단한 "for 루프"를 찾으십시오. 제 첫 번째 방법은 가장 초보자인데, 특히 초보자 인 경우 더욱 그렇습니다. – Matt

+0

코드를 복사/붙여 넣을 때 나쁘지 만 길지 만 float myvalue가 아닙니다. – Helvin

답변

3

를 오버라이드 (override)

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; 
     } 
    } 

} 
+0

목록에 elem이 하나만있는 경우 최대/최대 파인더가 작동합니까? NoSuchElementException이 발생하는 것 같습니다. – Helvin

+0

예, 요소가 하나 뿐인 경우에도 작동합니다. 'NoSuchElementException'는 사람들'ArrayList'가 비어있을 때만 발생합니다. –

+0

그래,이 방법을 시도하고 그것이 작동하는지 확인해 주셔서 감사합니다! – Helvin

0

힌트

implements Comparator<Person> 

을 다음 다음을 수행하십시오

public int compareTo(Object anotherPerson) throws ClassCastException { 
    if (!(anotherPerson instanceof Person)) 
     throw new ClassCastException("A Person object expected."); 
    int yourValue = ((Person) anotherPerson).getYourValue(); 
    return (this.yourValue - yourValue);  
    } 
+0

감사합니다. 내 두 번째 문제는 어떤 아이디어? – Helvin

+0

@Helvin리스트를 통해 for 루프를 실행하고 각 오브젝트를 다른 오브젝트와 비교하여 찾는다. 달과 연도를 찾으려면'getMonth()'와'getYear' 메쏘드를 사용하십시오 –

+0

당신의 솔루션을 min/max로 시도했지만 getValue가 float를 반환하고 compareTo가 int를 기다리고 있기 때문에 에러가 있습니다 – Helvin

0

는 Comparable 인터페이스를 구현

implements Serializable, Comparable<Person> 

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

이것은 당신이 최대 및 최소값 사람들에게 얼마나입니다 ... 당신은 사람들의 배열 목록을 가정하고 compareTo 메소드

@Override 
public int compareTo(Person o) { 
    int value = (int) o.getAge(); 
    return (int) (this.age - value); 
}