Reputation: 191
I am trying to figure out a way to get the maximum value of an attribute and its object reference from a list
containing custom objects.
Below is my code and I am supposed to use java 8 lambda expressions
here. I am not allowed to use any of the google guava libraries.
My question is how can I determine whether the sequenceNumber
attribute from CcarReportPreferenceConfig
objects is in a list.
The sequence number will be like 1 or 2 or 3 or 4
. If I have 5 objects of CcarReportPreferenceConfig
and if each objects sequence number is like 1,2,3,4,5
I need to determine that 5
is the largest of all
List<CcarReportPreferenceConfig> ccarReportPreferenceConfigs = ccarReportPrefConfigMapper.ccarReportPrefConfigDTOsToCcarReportPrefConfigs(ccarReportPrefConfigDTOList);
for (CcarReportPreferenceConfig ccarReportPreferenceConfig : ccarReportPreferenceConfigs) {
if (ccarReportPreferenceConfig.getSequenceNumber().intValue() == 1) {
ccarReportPreferenceConfig.setRejectSequence("DQM");
} else if (ccarReportPreferenceConfig.getSequenceNumber()==LargestNumber){
ccarReportPreferenceConfig.setRejectSequence("DQM");
} else {
ccarReportPreferenceConfig.setRejectSequence("S2");
}
}
Upvotes: 0
Views: 2083
Reputation: 4460
public class MaxFromAList {
int sequence = 0;
String code = "";
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public MaxFromAList(int sequence) {
this.sequence = sequence;
}
public int getSequence() {
return sequence;
}
public static void main(String[] args){
List<MaxFromAList> list = new ArrayList<MaxFromAList>();
list.add(new MaxFromAList(1111));
list.add(new MaxFromAList(2));
list.add(new MaxFromAList(654643));
list.add(new MaxFromAList(41));
list.add(new MaxFromAList(500));
list.stream().max(Comparator.comparing(MaxFromAList::getSequence))
.ifPresent(max -> max.setCode("MAXCODE"));
list.stream().filter(i -> !i.getCode().equals("MAXCODE")).forEach(ele -> setIdentificationCode(ele));
printMyList(list);
}
public static void setIdentificationCode(MaxFromAList element){
switch (element.sequence){
case 1:
element.setCode("DQM");break;
default:
element.setCode("");
}
}
public static void printMyList(List<MaxFromAList> mylist){
mylist.stream().forEach( o -> System.out.println("Sequence : " + o.sequence + " Code : "+ o.getCode()));
}
}
Upvotes: 3