Jason
Jason

Reputation: 794

How to iterate over a list to get specific attributes only

I have a list

List<Widget> specialWidgets = WidgetUtil.getInstance().findAllWidgetsForType(WidgetType.UNIQUE);

which returns a list with widgets ids and names

[Widget [id=4f90b95d-8eb3-41e0-b3b1-d9ea516e1012, name=blue widget]

How do I get just the ids into a list using java 7?

Upvotes: 0

Views: 93

Answers (3)

optuyvu
optuyvu

Reputation: 11

  • If you are using jkd8, using lambda expression to convert

List specialWidgetIds = WidgetUtil.getInstance().findAllWidgetsForType(WidgetType.UNIQUE).stream().map(p -> p.getId()).collect(Collectors.toList());

  • If you are using jdk7, jdk6... just do like pkamathk's suggestion.

Upvotes: 0

Pramod Mangalore
Pramod Mangalore

Reputation: 536

You need to iterate over the list that you just received from the service, pull out ID field from each Widget object and push that information into another List object.

List<Guid> specialWidgetsIds = new List<Guid>();

foreach (Widget w in specialWidgets) {
    specialWidgetsIds.Add(w.id);
}

Upvotes: 1

Trong Hoang
Trong Hoang

Reputation: 96

I think you should create new List and then add ids from specialWidgets to new List

Upvotes: 0

Related Questions