Search code examples
javalisthashmap

How to convert object to list with keys


I have a list in the following format

[{name=test1, id=something, row=1},
{name=test3, id=something, row=3},
{name=test2, id=something, row=2},
{name=test4, id=something, row=4}]

How can I find values according its keys, e.g. I need name from row 3... and also how can I sort it according row


Solution

  • Since your example is no valid json I assume that this should just represent the strucutre of the objects. So for a list with object of this class

    public class NamedRow {
        private String name;
        private String id;
        private int row;
    
        public int getRow() {
            return row;
        }
    
        // Other getters + setters
    }
    

    You can solve this with java streams:

    • Assuming the value of row is unique:
    // return null if not found
    public static NamedRow findSingle(List<NamedRow> list, int row){
            return list.stream()
                    .filter(namedRow -> namedRow.getRow() == row)
                    .findAny()
                    .orElse(null);
        }
    
    • Assuming the value of row is not unique:
    // returns empty list if no entry matches
    public static List<NamedRow> findMultiple(List<NamedRow> list, int row){
            return list.stream()
                    .filter(namedRow -> namedRow.getRow() == row)
                    .collect(Collectors.toList());
        }