E
E
evgenyt20002021-01-11 16:34:25
Java
evgenyt2000, 2021-01-11 16:34:25

How to cast ArrayList to List?

Good afternoon!
The situation is as follows. There is a result of one module in the form

static public ArrayList<Pair<String, String>> words = new ArrayList<>();

But I need these results in the form
public List <Lexeme> lexemeList
where
public class Lexeme {
    LexemeTypes type;
    String value;
 
    public Lexeme(LexemeTypes type, String value) {
        this.type = type;
        this.value = value;
    }
 
    public Lexeme(LexemeTypes type, Character value) {
        this.type = type;
        this.value = value.toString();
    }
    public Lexeme(LexemeTypes type, Integer value) {
        this.type = type;
        this.value = value.toString();
    }
 
    @Override
    public String toString() {
        return "Lexeme{" +
                "value='" + value + '\'' +
                ", type=" + type +
                '}';
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Vodakov, 2021-01-11
@evgenyt2000

Something like:

List<Lexeme> result=Lexemes.words.stream().map(
pair -> new Lexeme(pair.getKey(), pair.getValue())
).collect(Collectors.toList());

If your type was a string and not LexemeTypes
Since you did not specify what LexemeTypes is in the question, one can only guess. For example, this Enum
would then turn out like this:
List<Lexeme> result=Lexemes.words.stream().map(
pair -> new Lexeme(LexemeTypes.valueOf(pair.getKey()), pair.getValue())
).collect(Collectors.toList());

But, it would be more correct to create another constructor that will take a string as type and know how to turn it into the desired LexemeTypes

D
Denis Zagaevsky, 2021-01-11
@zagayevskiy

Use Stream API:

words.map(pair -> /* тут преобразуй пару в лексему по твоим правилам */).collect(Collectors.toList());

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question