流图以查找最新密钥的值

时间:2019-02-20 09:47:58

标签: java filter java-stream keyset

我有一个Map<Element, Attributes>,它由以下(示例)类和枚举的实例组成,在这里我想通过stream()获取最新键的值。最新的密钥可以由类creationTime的属性Element确定,并且Map中的相应值只是一个enum值:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Element implements Comparable<Element> {

    String abbreviation;
    LocalDateTime creationTime;

    public Element(String abbreviation, LocalDateTime creationTime) {
        this.abbreviation = abbreviation;
        this.creationTime = creationTime;
    }

    public String getAbbreviation() {
        return abbreviation;
    }

    public void setAbbreviation(String abbreviation) {
        this.abbreviation = abbreviation;
    }

    public LocalDateTime getCreationTime() {
        return creationTime;
    }

    public void setCreationTime(LocalDateTime creationTime) {
        this.creationTime = creationTime;
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Comparable#compareTo(java.lang.Object)
     */
    @Override
    public int compareTo(Element otherElement) {
        return this.creationTime.compareTo(otherElement.getCreationTime());
    }

    @Override
    public String toString() {
        return "[" + abbreviation + ", " + creationTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) + "]";
    }
}

请不要让Element implements Comparable<Element>仅使用LocalDateTime 的内置比较。

public enum Attributes {

    DONE,
    FIRST_REGISTRATION,
    SUBSEQUENT_REGISTRATION
}

我目前的方法只是能够过滤keySet并找到最新的密钥,然后我将其用于简单地在新代码行中获取值。我想知道是否可以在单个stream().filter(...)语句中使用

Map<Element, Attributes> results = new TreeMap<>();

// filling the map with random elements and attributes

Element latestKey = results.keySet().stream().max(Element::compareTo).get();
Attributes latestValue = results.get(latestKey);
  

我们可以通过在单个keySet语句中过滤Map的{​​{1}}来获得值吗?

stream()

其他信息 我不需要像Attributes latestValue = results.keySet().stream() .max(Element::compareTo) // what can I use here? .somehowAccessTheValueOfMaxKey() .get() 这样的默认值,因为null仅在它包含至少一个键值对时才被检查,这意味着总会有一个最近的元素-属性对,至少一对。

3 个答案:

答案 0 :(得分:5)

您可以找到最大Entry而不是最大密钥:

Attributes latestValue =
    results.entrySet()
           .stream()
           .max(Comparator.comparing(Map.Entry::getKey))
           .map(Map.Entry::getValue)
           .get();

答案 1 :(得分:5)

def download_outage_info_all(request):

    upload_data = download_data_form(request.POST)
    if upload_data.is_valid():
        print("valid")
        start = upload_data.cleaned_data['start_date_time']

        end = upload_data.cleaned_data['end_date_time']
        print(start, '-', end)

        start_timestamp = datetime.strptime(
            start, '%Y-%m-%d %H:%M')
        end_timestamp = datetime.strptime(
            end, '%Y-%m-%d %H:%M')

    try:
        info = planned_outages.objects.filter(
            start_timestamp__gte=start_timestamp, end_timestamp__lte=end_timestamp).values()
    except Exception as e:
        print("EXCEPTION", e)
        print("**** Data not found *** ")

    filename_date_part = datetime.now().strftime("%Y%m%d%H%M")

    response = HttpResponse(content_type='text/csv')

    response['Content-Disposition'] = 'attachment;filename=m_availability_' + \
                                      filename_date_part + '.csv'
    writer = csv.writer(response, delimiter=';')

    writer.writerow(['starts YYYY-mm-dd HH:MM:SS', 'time_zone',
                     'ends YYYY-mm-dd HH:MM:SS', 'asset id', 'availability type', 'PowerKW'])

    for x in info:

        try:
            unit_mw = unit_details.objects.get(
                unit_id=x['unit_id_id'])


            # prints to csv file
            writer.writerow([x['start_timestamp'], 'UTC',
                             x['end_timestamp'], unit_mw.unit_name,x['availability_type'], x['capacity_kw']])

        except Exception as e:
            print("EXCEPTION", e)
            print("**** Data not found for unit_mw*** ")

    return response

答案 2 :(得分:1)

您还可以将Collectors.toMapTreeMap一起用作地图工厂

Attributes value = results.entrySet().stream()
       .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> v1, TreeMap::new))
       .lastEntry().getValue();