Java 8 and above:

List<String> namesList = personList.stream()
                                   .map(Person::getName)
                                   .collect(Collectors.toList());

In Java 16+ you can end it with .toList()

If you need to make sure you get an ArrayList as a result, you have to change the last line to:

                                    ...
                                    .collect(Collectors.toCollection(ArrayList::new));

Java 7 and below:

The standard collection API prior to Java 8 has no support for such transformation. You'll have to write a loop (or wrap it in some "map" function of your own), unless you turn to some fancier collection API / extension.

(The lines in your Java snippet are exactly the lines I would use.)

In Apache Commons, you could use CollectionUtils.collect and a Transformer

In Guava, you could use the Lists.transform method.

Answer from aioobe on Stack Overflow
🌐
Coderanch
coderanch.com › t › 623127 › java › array-specific-attribute-values-list
How to get array of an specific attribute values from a list of object in java 7/8 (Features new in Java 8 forum at Coderanch)
November 4, 2013 - Hi guys, I have found the solution: Collection<String> names = CollectionUtils.collect(list, TransformerUtils.invokerTransformer("getName")); Here list is the list of someclass objects, getname is the getter method name of attribute "name" of someclass. Apache commons collections api is used here.
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › javax › management › AttributeList.html
AttributeList (Java Platform SE 7 )
Constructs an AttributeList containing the elements of the List specified, in the order in which they are returned by the List's iterator. ... IllegalArgumentException - if the list parameter is null or if the list parameter contains any non-Attribute objects.
🌐
CodingTechRoom
codingtechroom.com › question › java-8-transform-list-of-objects-to-list-of-attribute
How to Transform a List of Objects to a List of a Single Attribute in Java 8 - CodingTechRoom
What is the best way to extract ... · List<String> attributeList = objectList.stream() .map(MyClass::getAttribute) .collect(Collectors.toList()); In Java 8, you can easily transform a list of objects into a list that contains only a specific attribute from those objects using streams and the map method...
🌐
Oracle
docs.oracle.com › javase › tutorial › jndi › ops › getattrs.html
Read Attributes (The Java™ Tutorials > Java Naming and Directory Interface > Naming and Directory Operations)
You can then print the contents of this answer as follows. for (NamingEnumeration ae = answer.getAll(); ae.hasMore();) { Attribute attr = (Attribute)ae.next(); System.out.println("attribute: " + attr.getID()); /* Print each value */ for (NamingEnumeration e = attr.getAll(); e.hasMore(); System.out.println("value: " + e.next())) ; } This produces the following output. # java GetattrsAll attribute: sn value: Geisel attribute: objectclass value: top value: person value: organizationalPerson value: inetOrgPerson attribute: jpegphoto value: [B@1dacd78b attribute: mail value: Ted.Geisel@JNDITutorial.example.com attribute: facsimiletelephonenumber value: +1 408 555 2329 attribute: telephonenumber value: +1 408 555 5252 attribute: cn value: Ted Geisel
🌐
Iditect
iditect.com › faq › java › get-list-of-attributes-of-an-object-in-an-list-in-java.html
Get list of attributes of an object in an List in java
import java.lang.reflect.Field; ... person.setAddress("123 Main St"); // Get a list of attributes (fields) of the Person object List<String> attributesList = getAttributesList(person); // Print the list of attributes for (String attribute : attributesList) { System.out.printl...
Find elsewhere
🌐
Cmu
edelstein.pebbles.cs.cmu.edu › jadeite › main.php
AttributeList (Java Platform SE 6)
Represents a list of values for attributes of an MBean. The methods used for the insertion of {@link javax.management.Attribute Attribute} objects in the AttributeList overrides the corresponding methods in the superclass ArrayList. This is needed in order to insure that the objects contained in the AttributeList are only Attribute objects. This avoids getting an exception when retrieving elements from ...
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › javax › management › AttributeList.html
AttributeList (Java Platform SE 8 )
April 21, 2026 - Constructs an AttributeList containing the elements of the List specified, in the order in which they are returned by the List's iterator. ... IllegalArgumentException - if the list parameter is null or if the list parameter contains any non-Attribute objects.
Top answer
1 of 2
1

Your way looks fine. You can write it with less lines of code if you use Java 8 Streams, but that would require 4 iterations over the cards list instead of the single iteration you currently have.

For example, to create the list of counts, you can write :

List<Integer> counts = cards.stream().map(Card::getCount).collect(Collectors.toList());
2 of 2
1

If you are developing a set game, here is a solution for checking and completing card sets:

Card.java:

import java.util.Locale;

public final class Card {
    public static void main(String[] args) {
        Card a = new Card(Count.ONE, Color.RED, Fill.STRIPED, Shape.DIAMOND);
        Card b = new Card(Count.TWO, Color.RED, Fill.SOLID, Shape.DIAMOND);
        Card c = completeSet(a, b);
        System.out.println(c);
    }

    public int count;
    public int color;
    public int fill;
    public int shape;

    public Card() {

    }

    public Card(Count count, Color color, Fill fill, Shape shape) {
        setCount(count);
        setColor(color);
        setFill(fill);
        setShape(shape);
    }

    // getters and setters to operate with the attribute enumerations
    public Count getCount() {
        return Count.values()[count];
    }

    public Color getColor() {
        return Color.values()[color];
    }

    public Shape getShape() {
        return Shape.values()[shape];
    }

    public Fill getFill() {
        return Fill.values()[fill];
    }

    public void setCount(Count count) {
        this.count = count.ordinal();
    }

    public void setColor(Color color) {
        this.color = color.ordinal();
    }

    public void setShape(Shape shape) {
        this.shape = shape.ordinal();
    }

    public void setFill(Fill fill) {
        this.fill = fill.ordinal();
    }

    public static int completeAttribute(int a, int b) {
        if (a == b) {
            // attribute for each same
            return a;
        } else {
            // attribute for each different
            int c;
            for (c = 0; c < 3; c++) {
                if (c != a && c != b) {
                    break;
                }
            }
            return c;
        }
    }

    public static Card completeSet(Card a, Card b) {
        // determine missing card to make a set
        Card result = new Card();
        result.count = completeAttribute(a.count, b.count);
        result.color = completeAttribute(a.color, b.color);
        result.shape = completeAttribute(a.shape, b.shape);
        result.fill = completeAttribute(a.fill, b.fill);
        return result;
    }

    public static boolean isSet(Card a, Card b, Card c) {
        // check if it is a set by completing it
        return completeSet(a, b).equals(c);
    }

    @Override
    public boolean equals(Object that) {
        // currently unused
        if (this == that) {
            return true;
        }
        return that != null && that instanceof Card && this.equals((Card) that);
    }

    public boolean equals(Card that) {
        if (this == that) {
            return true;
        }
        return that != null
                && this.color == that.color
                && this.count == that.count
                && this.fill == that.fill
                && this.shape == that.shape;

    }

    @Override
    public int hashCode() {
        // currently unused
        int result = count;
        result = 31 * result + color;
        result = 31 * result + shape;
        result = 31 * result + fill;
        return result;
    }

    @Override
    public String toString() {
        // pretty print attributes
        String result = getCount() + " " + getColor() + " " + getFill() + " " + getShape();
        result = result.toLowerCase(Locale.ROOT);
        if(getCount() != Count.ONE) {
            result += "s";
        }
        return result;
    }

    // enumerations for pretty names
    public enum Count {
        ONE,
        TWO,
        THREE
    }

    public enum Color {
        RED,
        GREEN,
        VIOLET
    }

    public enum Shape {
        ELLIPSE,
        DIAMOND,
        TWIRL
    }

    public enum Fill {
        OPEN,
        STRIPED,
        SOLID
    }
}

Output: three red open diamonds

Top answer
1 of 2
5

If you are using Java 8, you can do:

private String[] getFields() {
    Class<? extends Component> componentClass = getClass();
    Field[] fields = componentClass.getFields();
    List<String> lines = new ArrayList<>(fields.length);

    Arrays.stream(fields).forEach(field -> {
        field.setAccessible(true);
        try {
            lines.add(field.getName() + " = " + field.get(this));
        } catch (final IllegalAccessException e) {
            lines.add(field.getName() + " > " + e.getClass().getSimpleName());
        }
    });

    return lines.toArray(new String[lines.size()]);
}

or to improve formatting:

private String[] getFields() {
    Class<? extends Component> componentClass = getClass();
    Field[] fields = componentClass.getFields();
    List<String> lines = new ArrayList<>(fields.length);

    Arrays.stream(fields)
            .forEach(
                    field -> {
                        field.setAccessible(true);
                        try {
                            lines.add(field.getName() + " = " + field.get(this));
                        } catch (final IllegalAccessException e) {
                            lines.add(field.getName() + " > "
                                    + e.getClass().getSimpleName());
                        }
                    });

    return lines.toArray(new String[lines.size()]);
}

Note that this is adding to @EricStein's excellent answer on normal concatenation instead of StringBuilders.

(I'm just starting to look into Streams, so if this is bad, please comment on why)

Otherwise...

Just a small comment:

lineBuilder.append(" = ");
lineBuilder.append(value);

can easily be:

lineBuilder.append(" = ").append(value);

Same with:

lineBuilder.append(" > ");
lineBuilder.append(e.getClass().getSimpleName());

becomes:

lineBuilder.append(" > ").append(e.getClass().getSimpleName());

Also, I would use a simple array instead of an ArrayList:

private String[] getFields() {
    Class<? extends Component> componentClass = getClass();
    Field[] fields = componentClass.getFields();
    String[] lines = new String[fields.length];

    int index = 0;
    for (Field field : fields) {
        StringBuilder lineBuilder = new StringBuilder();

        lineBuilder.append(field.getName());

        field.setAccessible(true);

        try {
            Object value = field.get(this);

            lineBuilder.append(" = ");
            lineBuilder.append(value);
        } catch (IllegalAccessException e) {
            lineBuilder.append(" > ");
            lineBuilder.append(e.getClass().getSimpleName());
        }

        lines[index++] = lineBuilder.toString();
    }

    return lines;
}

EDIT: The above review, if not using Java 8, should be replaced by @EricStein's code.

Also, getFields() is a bad name. Try getFieldDescriptions().

2 of 2
2

For getFields(), String concatenation is a not-unreasonable alternative you can consider. For toString(), using delete() is probably easier to read than the conditional check, there's probably no real performance gain due to branch prediction. It is distinctly wrong to merge the two methods. getFields() is probably not the best name, since it doesn't actually return the fields. Good names are hard, and nothing is jumping immediately to mind.

public abstract class Component {

    private String[] getFields() {
        final List<String> lines = new ArrayList<>();    
        for (final Field field: this.getClass().getFields()) {
            field.setAccessible(true);
            try {
                lines.add(field.getName() + " = " + field.get(this));
            } catch (final IllegalAccessException e) {
                lines.add(field.getName() + " > " + e.getClass().getSimpleName());
            }
        }
        return lines.toArray(new String[lines.size()]);
    }

    @Override
    public final String toString() {
        final StringBuilder builder = new StringBuilder(this.getClass().getSimpleName());

        builder.append('(');

        for (final String field : this.getFields()) {
            builder.append(field);
            builder.append(", ");
        }
        builder.delete(builder.length() - 2, builder.length());

        builder.append(')');

        return builder.toString();
    }
}
🌐
Java Guides
javaguides.net › 2024 › 05 › java-find-object-in-list-by-attribute.html
Java: Find Object in List by Attribute
May 29, 2024 - This guide will cover different ways to find an object in a list by an attribute, including using loops, the Stream API, and the Collections utility.
🌐
GT/CoC
sites.cc.gatech.edu › fce › contexttoolkit › documentation › javadoc › context › arch › storage › Attributes.html
: Class Attributes
This method takes a DataObject containing the list of attributes (names) wanted and it filters all the rest out from this Attributes object. ... Converts the attributes name-type pairs to a hashtable where the keys are the names and the values are the types. AKD - problem if two attributes have same name but different types · public java...
🌐
Play Java
playjava.wordpress.com › 2015 › 09 › 10 › extract-list-of-property-field-from-list-of-objects
Extract List of Property / Field from List of Objects | Play Java - Kickstart
September 10, 2015 - package com.playjava.util; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; /** * * @author abhishek.anne * @publish @ playjava.wordpress.com */ public class ReflectionUtil { /** * This method returns list of a field from list of inputlist * @author playjava.wordpress.com * @param inputlist * @param field * @return * @throws IntrospectionException * @throws NoSuchMethodE
🌐
Coderanch
coderanch.com › t › 441765 › java › Loop-list-objects-attribute
Loop through the list of objects to get attribute. (Beginning Java forum at Coderanch)
April 19, 2009 - Well, you can use a for-each loop for this purpose like below: But this is not a good practice, because you can use Map classes instead of those List classes, so you can get the student quickly and in a smart-way without having a loop. Devaka. Author of ExamLab - a free SCJP / OCPJP exam simulator What would SCJP exam questions look like? -- OCPJP Online Training -- Twitter -- How to Ask a Question ... hmm I have problem , it repeats enterMarkC for every Student in the list, check for student numbber work... Currently I am trying to set the attribute of Student class (courseworkMark) by user input.