Total Pageviews

2016/05/07

Java enum for loop example

Assume I have a enumeration, how do I iterate over all values in enumeration and convert to List of ServiceType bean?

ServiceTypeEnum is as bellows:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package albert.practice.enums;

import lombok.AllArgsConstructor;
import lombok.Getter;

@AllArgsConstructor
public enum ServiceTypeEnum {

    SMS("SMS", "OTP簡訊發送服務"), EMAIL("EMAIL", "電子郵件發送服務"), TIF("TIF", "檔案調閱服務");

    @Getter
    private String type;

    @Getter
    private String name;

ServiceType bean looks like this:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package albert.practice.enums;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.ToString;

@Data
@ToString
@AllArgsConstructor
public class ServiceType {

    private String type;
    private String name;

}


Test client looks like this:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package albert.practice.enums;

import java.util.ArrayList;
import java.util.List;

public class InterateEnumsTest {

    public static void main(String[] args) {

        List<ServiceType> serviceTypes = new ArrayList<ServiceType>();

        for (ServiceTypeEnum serviceType : ServiceTypeEnum.values()) {
            ServiceType bean = new ServiceType(serviceType.getType(), serviceType.getName());
            serviceTypes.add(bean);
        }

        System.out.println(serviceTypes.toString());
    }
}

Console
1
[ServiceType(type=SMS, name=OTP簡訊發送服務), ServiceType(type=EMAIL, name=電子郵件發送服務), ServiceType(type=TIF, name=檔案調閱服務)]



Reference

No comments: