【问题标题】:Separate a field from list and make a new list从列表中分离一个字段并创建一个新列表
【发布时间】:2019-12-23 05:52:36
【问题描述】:

我有这个:

 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<"Some thing"> combined = new ArrayList();
combined is like this :
USA
SF
NY
India
Mumbai 
Agra 

我使用了这种方法:

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);
    }
}

}

任何更好、更清洁、更快的方法

【问题讨论】:

  • 它已经在那里了
  • 即使有人使用比较器根据您的 India、Mumbai 和 Agra 对您进行排序,那么美国的城市也会失败。
  • 如果您的疑问尚未消除,请告诉我们。

标签: java performance java-8 coding-style


【解决方案1】:
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);
    }
}

【讨论】:

    【解决方案2】:
    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);
                }
    
            }
    
        }
    }
    

    输出

    USA
    SF
    NY
    India
    Agra
    Mumbai
    

    【讨论】:

    • 应该是国名城市名(国家以上)城市名(国家以上)国名城市名(国家以上)城市名(国家以上)
    • 肯定可以,前面没提过,反正我试试看。
    【解决方案3】:
        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);
                }
    
    
    
    
    
        }
    
    }
    

    输出

    USA
    SF
    NY
    India
    Agra
    Mumbai
    

    【讨论】:

      【解决方案4】:

      请试试这个。

      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);});
      

      输出:

      USA
      SF
      NY
      India
      Agra
      Mumbai
      

      【讨论】:

      • 这完成了 80% 的事情,现在您需要以正确的方式打印。
      • 这应该可以。 countryListHashMap.forEach((k,v) -> {System.out.println(k);v.forEach(System.out::println);});
      猜你喜欢
      • 2019-11-29
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 2016-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多