2

How get to only cspId in to one list of integer using Java stream API. Here in below example manually added enums in to list usually i will get from method calling place.

 public class Test {
        public static void main(String args[]){
            List<Board> numbers=new ArrayList<>();
            numbers.add(Board.MY_BOARD);
            numbers.add(Board.TEST_BOARD);
            List<Integer> list=new ArrayList<Integer>();//Here i want to get List<integer> using jaba stream api.
            System.out.println(list);               
            }
        }

Enum of Board

    enum Board{
          MY_BOARD(0, "My Dashboard"),
          WEB_BOARD(1, "web Dashboard"),
          TEST_BOARD(2, "web Dashboard")
    ;    
          private int cspId;
          private String name;

          Board(int id, String name) {
            this.cspId = id;
            this.name = name;
          }
          public int getId() {
                return cspId;
              }
              public String getName() {
                return name;
              }           
    }
1
  • 6
    ... .stream().map(Board::getId).collect(toList())? Commented May 9, 2019 at 11:43

2 Answers 2

8

Convert enum array to stream

Stream.of(Enum.values()).map....

for your example would be:

List<Integer> list= Stream.of(Board.values()).map(Board::getId).collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

1 Comment

Board::getId - no parenthesis
6

Then use the Stream API:

List<Integer> list = numbers.stream().map(Board::getId).collect(toList());

1 Comment

Just to elaborate a bit more and get rid of numbers completely, it could be List<Integer> list = Arrays.asList(Board.values()).stream().map(Board::getId).collect(Collectors.toList());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.