Kylo Fernao
Kylo Fernao

Reputation: 35

How to convert List<Object> to List<Object.String> i.e List<String>?

Im new in java

Lets say I have

class OnlyNotes {
        String notes;
    }

and

List<OnlyNotes>;

how to convert it to:

List<String>

That contains list of notes

Upvotes: 0

Views: 80

Answers (2)

Michael Katt
Michael Katt

Reputation: 643

Assumning your class looks like

class OnlyNotes {

  String notes;

  private OnlyNotes(String pNotes) {
     super();
     notes = pNotes;
  }

  public String getNotes() {
     return notes;
  }
}

you could do that by using for-loop or by using stream

List<OnlyNotes> onlyNotesList =
            Arrays.asList(new OnlyNotes("first"), new OnlyNotes("second"), new OnlyNotes("third"));

List<String> onlyNotesAsStringList = new ArrayList<>();
for (OnlyNotes onlyNotes : onlyNotesList) {
         onlyNotesAsStringList.add(onlyNotes.getNotes());
}

List<String> onlyNotesAsStringByStreamList = onlyNotesList.stream().map(OnlyNotes::getNotes).collect(Collectors.toList());

Upvotes: 0

Sebastian Qu
Sebastian Qu

Reputation: 36

You can write like this.

List<OnlyNotes> onlyNotes = new ArrayList<>();
List<String> newStrings = onlyNotes.stream.map(e -> e.notes).collect(Collectors.toList());

Upvotes: 2

Related Questions