将对象列表根据对象字段的唯一值数量分成n个列表的方法是否存在?

huangapple go评论79阅读模式
英文:

Is there a way to split a list of objects into n number of lists depending on the number of unique values of an object field?

问题

I have a method that returns a list of objects.

In that object, there is a String field orderType.

Is there a way for me to separate that list into n number of lists depending on the unique values of orderType?

For example, if the method returns a list containing 10 objects, then 4 of them have an orderType value of x, 3 have an orderType value of y, and another 4 have a value of z.

Then the result will be 3 lists containing 4, 3, 4 objects respectively.

orderType does not only have x, y, and z as possible values.

I am having a hard time putting this into actual code, but my idea is like this:

List<Orders> orderList = getOrder();

for (int i = 0; i < orderList.size(); i++) {

   if (orderList.get(i).orderType is unique) {
       create a new list
   } else {
       add to an existing list having the same orderType
   }
}
英文:

I have a method that returns a list of objects.

In that object, there is a String field orderType.

Is there a way for me to separate that list into n number of lists depending on the unique values of orderType?

For example the method returns a list containing 10 objects, then 4 of them has orderType value of x, 3 has orderType value of y, then another 4 has a value of z.

then the result will be 3 lists containing 4,3,4 objects respectively

orderType does not only have x, y and z as possible values.

i am having a hard time putting this into an actual code but my idea is like this

List&lt;Orders&gt; orderList = getOrder();


for(int i=0; i&lt;orderList.size();i++){

   if(orderList.get(i).orderType is unique){
        create a new list
   }else{
        add to an existing list having the same orderType
   }
}

答案1

得分: 1

以下是翻译后的代码部分:

我建议使用这个相对通用的函数

```java
public static <T, U> Map<U, List<T>> getLists(List<T> values, Function<T, U> orderBy) {
    Map<U, List<T>> lists = new HashMap<>();
    for (T value : values) {
        U type = orderBy.apply(value);
        if (!lists.containsKey(type)) {
            lists.put(type, new ArrayList<>());
        }
        lists.get(type).add(value);
    }
    return lists;
}

订单类:

class Order {

    private String orderType;
    private String name;

    public Order(String orderType, String name) {
        this.orderType = orderType;
        this.name = name;
    }

    public String getOrderType() {
        return orderType;
    }

    public String getName() {
        return name;
    }

}

如何使用:

public static void main(String args[]){
    List<Order> orders = new ArrayList<>();
    orders.add(new Order("TYPE1", "Order1"));
    orders.add(new Order("TYPE2", "Order2"));
    orders.add(new Order("TYPE1", "Order3"));
    orders.add(new Order("TYPE1", "Order4"));
    orders.add(new Order("TYPE2", "Order5"));
    orders.add(new Order("TYPE1", "Order6"));
    orders.add(new Order("TYPE1", "Order7"));
    orders.add(new Order("TYPE1", "Order8"));

    Map<String, List<Order>> map =  getLists(orders, Order::getOrderType);

    for (String key : map.keySet()) {
        System.out.println(key);
        for (Order order : map.get(key)) {
            System.out.println(order.getOrderType() + " " + order.getName());
        }
        System.out.println();
    }
}

请注意,代码中的HTML实体(如&lt;&quot;)已被移除,以便更好地显示代码。

英文:

I'd suggest this rather general function:

    public static &lt;T, U&gt; Map&lt;U, List&lt;T&gt;&gt; getLists(List&lt;T&gt; values, Function&lt;T, U&gt; orderBy) {
        Map&lt;U, List&lt;T&gt;&gt; lists = new HashMap&lt;&gt;();
        for (T value : values) {
            U type = orderBy.apply(value);
            if (!lists.containsKey(type)) {
                lists.put(type, new ArrayList&lt;&gt;());
            }
            lists.get(type).add(value);
        }
        return lists;
    }

Order Class:

class Order {

        private String orderType;
        private String name;

        public Order(String orderType, String name) {
            this.orderType = orderType;
            this.name = name;
        }

        public String getOrderType() {
            return orderType;
        }

        public String getName() {
            return name;
        }

    }

How to use:

    public static void main(String args[]){
        List&lt;Order&gt; orders = new ArrayList&lt;&gt;();
        orders.add(new Order(&quot;TYPE1&quot;, &quot;Order1&quot;));
        orders.add(new Order(&quot;TYPE2&quot;, &quot;Order2&quot;));
        orders.add(new Order(&quot;TYPE1&quot;, &quot;Order3&quot;));
        orders.add(new Order(&quot;TYPE1&quot;, &quot;Order4&quot;));
        orders.add(new Order(&quot;TYPE2&quot;, &quot;Order5&quot;));
        orders.add(new Order(&quot;TYPE1&quot;, &quot;Order6&quot;));
        orders.add(new Order(&quot;TYPE1&quot;, &quot;Order7&quot;));
        orders.add(new Order(&quot;TYPE1&quot;, &quot;Order8&quot;));

        Map&lt;String, List&lt;Order&gt;&gt; map =  getLists(orders, Order::getOrderType);

        for (String key : map.keySet()) {
            System.out.println(key);
            for (Order order : map.get(key)) {
                System.out.println(order.getOrderType() + &quot; &quot; + order.getName());
            }
            System.out.println();
        }
    }

答案2

得分: 0

我认为更容易将元素提取到一个Map中,然后您可以利用Collectors.toMap的第三个参数,将相同键的值合并起来。

public void tryIt() {
    // 给定类
    class Foo {
        String x;

        Foo(String x) {
            this.x = x;
        }

        @Override
        public String toString() {
            return this.x;
        }
    }
    List<Foo> foos = new ArrayList<>();
    IntStream.range(0, 4).forEach(i -> {
        foos.add(new Foo("x"));
        foos.add(new Foo("z"));
    });
    IntStream.range(0, 3).forEach(i -> foos.add(new Foo("y")));

    // 创建一个元素到原始对象列表的映射,根据相同的元素键进行分组
    Map<String, List<Foo>> collect = foos.stream().collect(Collectors.toMap(
            f -> f.x,
            Collections::singletonList,
            (l1, l2) -> Stream.concat(l1.stream(), l2.stream()).collect(Collectors.toList())));

    System.out.println(collect);
}

输出

{x=[x, x, x, x], y=[y, y, y], z=[z, z, z, z]}
英文:

I think it's easier to pull out the element to a Map, then you can take advantage of the Collectors.toMap third parameter that combines the values of the same key.

public void tryIt() {
    // given
    class Foo {
        String x;

        Foo(String x) {
            this.x = x;
        }

        @Override
        public String toString() {
            return this.x;
        }
    }
    List&lt;Foo&gt; foos = new ArrayList&lt;&gt;();
    IntStream.range(0, 4).forEach(i -&gt; {
        foos.add(new Foo(&quot;x&quot;));
        foos.add(new Foo(&quot;z&quot;));
    });
    IntStream.range(0, 3).forEach(i -&gt; foos.add(new Foo(&quot;y&quot;)));

    // create a mapping of element, to list of original object, grouping by same element key
    Map&lt;String, List&lt;Foo&gt;&gt; collect = foos.stream().collect(Collectors.toMap(
            f -&gt; f.x, 
            Collections::singletonList,
            (l1, l2) -&gt; Stream.concat(l1.stream(), l2.stream()).collect(Collectors.toList())));

    System.out.println(collect);
}

Output

{x=[x, x, x, x], y=[y, y, y], z=[z, z, z, z]}

huangapple
  • 本文由 发表于 2020年8月2日 11:49:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/63212205.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定