簡體   English   中英

從Rest API獲取列表

[英]Get List from rest api

我想從rest api獲取時區作為列表。 我嘗試了這個:

@GetMapping("timezone")
    public ResponseEntity<?> getTimezone() {
        return ResponseEntity.ok(timezoneService.getTimezoneList().entrySet().stream()
                .map(g -> new AcquirerTimezoneDTO(g.getKey())).collect(Collectors.toList()));
    }

DTO:

public class AcquirerTimezoneDTO {

    private String timezone;

    public AcquirerTimezoneDTO(String timezone) {
        this.timezone = timezone;
    }

    public String getTimezone() {
        return timezone;
    }

    public void setTimezone(String timezone) {
        this.timezone = timezone;
    }
}

服務:

@Service
public class TimezoneService {

    public List<String> getTimezoneList() {

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

        String[] allTimeZones = TimeZone.getAvailableIDs();

        Arrays.sort(allTimeZones);

        for (int i = 0; i < allTimeZones.length; i++) {
            list.add(allTimeZones[i]);
        }

        return list;
    }
}

但是我對.entrySet()遇到錯誤對於類型List,方法entrySet()未定義

您知道如何解決此問題嗎?

entrySet()Maps擁有的方法,而不是Lists

只需直接在列表上使用stream()方法,而無需使用entrySet() ,如下所示:

return ResponseEntity.ok(timezoneService.getTimezoneList().stream()
                .map(g -> new AcquirerTimezoneDTO(g.getKey())).collect(Collectors.toList()));

您需要將api調用從timezoneService.getTimezoneList().entrySet().stream()更改為timezoneService.getTimezoneList().stream()

列表的api沒有entrySet()

您可以直接在列表上使用流:

@GetMapping("timezone")
public ResponseEntity<?> getTimezone() {
    return ResponseEntity.ok(timezoneService.getTimezoneList().stream()
            .map(g -> new AcquirerTimezoneDTO(g.getKey())).collect(Collectors.toList()));
}

另外,List接口不包含entrySet方法,因此會導致崩潰。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM