简体   繁体   English

从列表中分离一个字段并创建一个新列表

[英]Separate a field from list and make a new list

I have this :我有这个 :

 List<City> cities = new ArrayList<>();
    cities.add(new City("SF","USA"));
    cities.add(new City("Agra","India"));
    cities.add(new City("Mumbai","India"));
    cities.add(new City("NY","USA"));

Required Output:所需输出:

List<"Some thing"> combined = new ArrayList();
combined is like this :
USA
SF
NY
India
Mumbai 
Agra 

I used this approach :我使用了这种方法:

public class ListBreak {
public static void main(String[] args) {

    List<City> cities = new ArrayList<>();
    cities.add(new City("SF","USA"));
    cities.add(new City("Agra","India"));
    cities.add(new City("Mumbai","India"));
    cities.add(new City("NY","USA"));

    List<ABC> abcs = new ArrayList<>();
    HashMap<Country,List<City>> countryListHashMap= new HashMap<>();
    // way one
    for (City city:cities) {
         Country coutry= new Country(city.countryName);
        if(!countryListHashMap.containsKey(coutry))
        {
            countryListHashMap.put(coutry,new ArrayList<>());
        }
        List<City> list = countryListHashMap.get(coutry);
        list.add(city);
        countryListHashMap.put(coutry,list);
    }
    for (Map.Entry<Country,List<City>> entrySet:countryListHashMap.entrySet()) {
          abcs.add(entrySet.getKey());
          abcs.addAll(entrySet.getValue());
    }
    System.out.println(abcs);
}
static class City implements ABC{
    String cityName;
    String countryName;

    public City(String cityName, String countryName) {
        this.cityName = cityName;
        this.countryName = countryName;
    }
}
static class Country implements ABC{
    String countryName;

    public Country(String countryName) {
        this.countryName = countryName;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Country)) return false;
        Country country = (Country) o;
        return countryName.equals(country.countryName);
    }

    @Override
    public int hashCode() {
        return Objects.hash(countryName);
    }
}

} }

Any better, cleaner, faster way任何更好、更清洁、更快的方式

package clean.code;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;

public class ListBreak {

    public static class City {

        private String cityName;
        private String countryName;

        public City(String cityName, String countryName) {
            this.setCityName(cityName);
            this.setCountryName(countryName);
        }

        public String getCityName() {
            return cityName;
        }

        public void setCityName(String cityName) {
            this.cityName = cityName;
        }

        public String getCountryName() {
            return countryName;
        }

        public void setCountryName(String countryName) {
            this.countryName = countryName;
        }

    }

    public static void main(String[] args) {

        List<City> cities = new ArrayList<>();

        cities.add(new City("SF", "USA"));
        cities.add(new City("Agra", "India"));
        cities.add(new City("Mumbai", "India"));
        cities.add(new City("NY", "USA"));

        cities.stream()
                .collect(Collectors.groupingBy(City::getCountryName, collectCityNames()))
                .forEach((countryName, cityNames) -> printCityNamesByCountryName(countryName, cityNames));
    }

    private static Collector<City, ?, List<String>> collectCityNames() {
        return Collectors.mapping(City::getCityName, Collectors.toList());
    }

    private static void printCityNamesByCountryName(String countryName, List<String> cityNames) {
        System.out.println(countryName);
        cityNames.forEach(System.out::println);
    }
}
class City {
    String cityName;
    String countryName;

//Getter,Setter and Constructors
}

public class CandidateCode {
    public static void main(String[] args) {
        List<City> cities = new ArrayList<>();
        //stuffs
        final Map<String, List<String>> collect1 = cities.stream()
                .collect(Collectors.groupingBy(City::getCountryName, Collectors.mapping(City::getCityName, Collectors.toList())));
        for (Map.Entry str : collect1.entrySet()) {
            System.out.println(str.getKey());
            for (String s : collect1.get(str.getKey())) {
                System.out.println(s);
            }

        }

    }
}

Output :输出

USA
SF
NY
India
Agra
Mumbai
    class City{

        String cityName;
        String countryName;
        public String getCityName() {
            return cityName;
        }
        public void setCityName(String cityName) {
            this.cityName = cityName;
        }
        public String getCountryName() {
            return countryName;
        }
        public void setCountryName(String countryName) {
            this.countryName = countryName;
        }

        public City(String string, String string2) {
            this.cityName = string;
            this.countryName=string2;

        }

        //getter setter ns constructor stuffs

     }
    public class Test  {
        public static void main(String[] args) {
            List<City> cities = new ArrayList<>();
            cities.add(new City("SF","USA"));
            cities.add(new City("Agra","India"));
            cities.add(new City("Mumbai","India"));
            cities.add(new City("NY","USA"));
            List<String> result = new ArrayList<>();

            Map<String, List<City>> res = cities.stream().collect(Collectors.groupingBy(City::getCountryName));
            for(HashMap.Entry<String, List<City>> valuepair:res.entrySet())
            {
                List<City> value = valuepair.getValue();
                City countryName = value.get(0);
                String cname = countryName.getCountryName();
                result.add(cname);
                for (City count : value) {
                    result.add(count.getCityName());

                }

            }
            for (String string : result) {
                System.out.println(string);
            }





    }

}

Output输出

USA
SF
NY
India
Agra
Mumbai

Please try this.请试试这个。

Map<String, List<String>> countryListHashMap =
                cities.stream().collect(Collectors.groupingBy(City::getCountryName, Collectors.mapping(City::getCityName, Collectors.toList())));
countryListHashMap.forEach((k,v)-> {System.out.println(k);
            v.forEach(System.out::println);});

Output:输出:

USA
SF
NY
India
Agra
Mumbai

从列表中获取 Object<object> 如果 Object 中的特定字段与单独列表中的任何值匹配<div id="text_translate"><p>我有一个字符串列表,其中包含所有商店编号:</p><pre> List&lt;String&gt; stores = new ArrayList&lt;&gt;;</pre><p> 还有一个对象列表,例如:</p><pre> List&lt;UserStores&gt; userStores = new ArrayList&lt;&gt;;</pre><p> 现在,这个 UserStores class 看起来像这样:</p><pre> public class UserStores { private String storeNo; private String storeName; private String country; }</pre><p> 如果上面给出的“商店”列表中存在任何 storeNo,我想从此List&lt;UserStores&gt;中获取所有用户商店。</p><p> 例如,</p><pre> stores = {1,2}; UserStores = [ {2, qwe, wqew}, {1,ABC, India}, {3, asd, USA} ]; expected result = [{1,ABC, India}, {2, qwe, wqew}]; in the order of stores present in 'stores' list,</pre><p> 我怎样才能使用流/收集器得到这个?</p><p> 我当前的代码是这样的……可以改进吗?</p><pre> private static List&lt;UserStores&gt; getModifiedUserStoresList( List&lt;String&gt; stores, List&lt;UserStores&gt; userStores ) { List&lt;UserStores&gt; userStoreList = new ArrayList&lt;&gt;(); for(int i = 0; i &lt; stores.size(); i++) { for(int j = 0; j &lt; userStores.size(); j++) { if(userStores.get(j).getStoreNo().equals(stores.get(i))) { userStoreList.add(userStores.get(j)); break; } } } return userStoreList; }</pre></div></object> - Get Object from List<Object> if a particular field in Object matches any value from a separate list

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Kotlin:如何将列表中的字段 map 到新列表并将其分组 - Kotlin: How to map a field from list to a new list and group it 在列表中制作相同对象的单独列表 - Make separate list of same object in the list 如何从 ArrayList 的列表中创建一个新的 ArrayList 列表? - How to make a new List of ArrayList from a List of ArrayList? 从列表中获取 Object<object> 如果 Object 中的特定字段与单独列表中的任何值匹配<div id="text_translate"><p>我有一个字符串列表,其中包含所有商店编号:</p><pre> List&lt;String&gt; stores = new ArrayList&lt;&gt;;</pre><p> 还有一个对象列表,例如:</p><pre> List&lt;UserStores&gt; userStores = new ArrayList&lt;&gt;;</pre><p> 现在,这个 UserStores class 看起来像这样:</p><pre> public class UserStores { private String storeNo; private String storeName; private String country; }</pre><p> 如果上面给出的“商店”列表中存在任何 storeNo,我想从此List&lt;UserStores&gt;中获取所有用户商店。</p><p> 例如,</p><pre> stores = {1,2}; UserStores = [ {2, qwe, wqew}, {1,ABC, India}, {3, asd, USA} ]; expected result = [{1,ABC, India}, {2, qwe, wqew}]; in the order of stores present in 'stores' list,</pre><p> 我怎样才能使用流/收集器得到这个?</p><p> 我当前的代码是这样的……可以改进吗?</p><pre> private static List&lt;UserStores&gt; getModifiedUserStoresList( List&lt;String&gt; stores, List&lt;UserStores&gt; userStores ) { List&lt;UserStores&gt; userStoreList = new ArrayList&lt;&gt;(); for(int i = 0; i &lt; stores.size(); i++) { for(int j = 0; j &lt; userStores.size(); j++) { if(userStores.get(j).getStoreNo().equals(stores.get(i))) { userStoreList.add(userStores.get(j)); break; } } } return userStoreList; }</pre></div></object> - Get Object from List<Object> if a particular field in Object matches any value from a separate list 根据对象的字段分离数组列表 - Separate Array list based on object's field 在List的某个字段上创建addAll() - Make addAll() on a certain field of a List 从序列化列表字段到列表字段对象化 - From serialized list field to list field objectify 如何在 Java 中创建一个新的 List - How to make a new List in Java 如何迭代对象列表以从中创建新Map? - How to iterate a list of an object to make a new Map from it? 如何构建一个新列表,其中包含现有列表中的所有条目以及修改了一个字段的每个条目的副本? - How to build a new list containing all entries from existing list AND a copy of each entry with one field modified?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM